【发布时间】:2015-06-08 16:36:33
【问题描述】:
我正在尝试使用 PHP 和 AngularJS 在 HTML 页面中显示数据。这是 PHP 代码:
<?php
$mysqli = mysqli_connect("localhost", "root", "admin", "webstore");
if(mysqli_connect_errno()){
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$output = array();
$json = array();
$result = mysqli_query($mysqli, 'SELECT * FROM products');
while($row = mysqli_fetch_assoc($result)) {
$output = array(
'id'=>$row['id'],
'code'=>$row['product_code'],
'image'=>$row['product_image'],
'price'=>$row['price']
);
array_push($json, $output);
}
header('Content-Type: application/json');
echo json_encode($json);
?>
这是来自 controller.js 的代码
controller('MainController', function($scope,$http) {
$http.get('prod.php').success(function(response){
$scope.items = response;
console.log(response);
});
所以一切都很好地显示在我的 HTML 页面上,但是当我添加到数组时
$row['name'] && $row['description']
console.log(response) 和 echo json_encode($json) 都是空的。但是,如果我只写print_r($json),它会打印出正确的结果。
所以我不知道为什么json_encode() 不接受这两列。任何帮助都会很好。
更新
为了清楚起见,我在查看查询结果时尝试将$row['name'] && $row['description'] 添加到$output 数组中。所以它会是这样的:
$output = array(
'id'=>$row['id'],
'code'=>$row['product_code'],
'image'=>$row['product_image'],
'price'=>$row['price'],
'name'=>$row['name'],
'description'=>$row['description']
);
但正如我所说,由于某种原因,这不起作用。
我的数据库表结构如下:
+-------------------------------------+
| id | int(11) primary key |
| product_code | varchar(50) |
| name | varchar(50) |
| description | text |
| price | double |
| product_image | varchar(50) |
+-------------------------------------+
【问题讨论】:
-
你能显示你的
product数据库表的结构吗?另外,您能否显示将$row['name']和$row['description']添加到响应中的代码?这可能会有所帮助。 -
你在哪里添加 $row['name'] && $row['description'] 这也会返回一个布尔值。
-
json_last_error() 结果 (php.net/manual/en/function.json-last-error.php) 告诉你什么?如果有的话?
-
打印的是“5”,所以看起来是JSON_ERROR_UTF8
-
你能把你的答案放在提供的答案框中吗?这比将答案编辑到问题中更可取,因为它保留在“未回答”池中。