我想从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);
}
你生成的JSON是什么样的? –
什么是具体问题,它是如何“不工作”? –
问题很简单,当脚本运行时崩溃导致网页无法加载。 JSON对象只是一个没有密钥的值(品牌)列表。 –