json_encode()拒绝两个MySQL列

时间:2015-04-03 15:04:24

标签: php mysql json angularjs

我正在尝试使用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']&amp;&amp;当我通过查询结果时,$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)         |
+-------------------------------------+

1 个答案:

答案 0 :(得分:0)

我能够通过添加

来解决这个问题
mysqli_set_charset('utf8)

现在一切正常:

<?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);   
}

mysqli_set_charset('utf8);
header('Content-Type: application/json');
echo json_encode($json);

?>