2013-06-29 50 views
0

我想从mySQL数据库中检索项目列表,并将它们作为列表插入到网页上的选定对象中。以下是一些无法正常工作的代码。使用php检索项目列表

在第一行中,我试图从我创建的名为DatabaseInterface的单例对象中的名为getBrands()的公共函数中检索JSON对象。

第二行然后试图将该JSON对象变成一个php数组。

最后,我运行一个循环,可以选择网页标签之间的每个项目。

我哪里错了?

<?php 

var $brandArrayJSON = DatabaseInterface::getBrands(); 
$brandArray = JSON_decode($brandArrayJSON); 

for ($loop=0; $loop < sizeof($brandArray); $loop++) { 
    echo "<option>$brandArray[$loop]</option>"; 
} 

?> 

编辑︰万一它有帮助,这里是我的DatabaseInterface单身人士。我已经包含在我的PHP文件

class databaseInterface { 

private static $_instance; 

// Private constructor prevents instantiation 
private function __construct() { 
} 

public static function getInstance() { 
    if (!self::$_instance) { 
     self::$_instance = mysqli_connect(self::databaseHost, self::databaseUsername, self::databasePassword, self::databaseName); 
     if (mysqli_connect_errno(self::$_instance)) { 
      throw new Exception("Failed to connect to MySQL:" . mysqli_connect_error()); 
     } 
    } 
    return self::$_instance; 
} 

public function getBrands() { 

    try { 
     $con = DatabaseInterface::getInstance(); 
    } catch (Exception $e) { 
     // Handle exception 
     echo $e->getMessage(); 
    } 

    $query = "SELECT psBrandName from brands"; 
    $result = mysqli_query($con, $query) or die ("Couldn't execute query. ".mysqli_error($con)); 

    $resultArray[] = array(); 

    while ($row = mysqli_fetch_assoc($result)) { 

     extract($row); 
     $resultArray[] = $psBrandName; 

    } 

    return json_Encode($resultArray); 

} 
+1

你生成的JSON是什么样的? –

+1

什么是具体问题,它是如何“不工作”? –

+0

问题很简单,当脚本运行时崩溃导致网页无法加载。 JSON对象只是一个没有密钥的值(品牌)列表。 –

回答

0

顶这个文件没有什么“错误”的代码是,因为它应该工作(前提是没有任何的查询方打破)。但是,有几件事情应该改进。

首先,基本上什么getBrands()方法做的是相同的:

$brandArray = json_encode(array('test','test2','test3')); 
echo $brandArray; // returns ["test","test2","test3"] 

现在,当你解码,你得到你最初投入(数组)同样的事情:

$brandArray = json_decode('["test","test2","test3"]'); 
var_dump($brandArray); // Will dump an array 

由于这是一个数组(而不是一个PHP对象),因此您可以使用foreach。

foreach($brandArray as $option) { 
    echo '<option>', $option, '</option>'; 
} 

如果你担心它是在某些情况下(也许你有一个非数组对象JS这将是大多相当于一个PHP关联数组)的对象,你可以施放json_decode结果成数组。现在

$brandArray = (array)$brandArray; 

,在你getBrands()方法,我会强烈建议只使用$row['psBrandName'],而不是混乱的事情了extract,除非你有一个很好的理由这样做。