如何正确使用PHP将MySQL对象编码为JSON?

时间:2012-08-09 22:09:31

标签: php mysql json mysqli

我正在尝试迭代MySQL对象并在另一个页面上使用ajax调用来追加数据,但是我无法让php将有效的JSON返回给回调。

这显然不起作用......

<?php

    $db_host = "localhost";
    $db_user = "blah";
    $db_pass = "blah";
    $db_name = "chat";
    $mysqli = new MySQLi($db_host, $db_user, $db_pass, $db_name);
    $myQuery = "SELECT * FROM users";
    $result = $mysqli->query($myQuery) or die($mysqli->error);
    $row = $result->fetch_assoc();
    echo json_encode($row);

?>

或者这个......

<?php

    $db_host = "localhost";
    $db_user = "blah";
    $db_pass = "blah";
    $db_name = "chat";
    $mysqli = new MySQLi($db_host, $db_user, $db_pass, $db_name);
    $myQuery = "SELECT * FROM users";
    $result = $mysqli->query($myQuery) or die($mysqli->error);
    while ( $row = $result->fetch_assoc() ){
        echo json_encode($row) . ", ";
    }

?>

3 个答案:

答案 0 :(得分:9)

$data = array();

while ( $row = $result->fetch_assoc() ){
    $data[] = json_encode($row);
}
echo json_encode( $data );

这应该这样做。此外,您可以使用http://jsonlint.com/查看JSON输出的问题。

使用fetch_all()

更新也可能是一个好主意

$data = $result->fetch_all( MYSQLI_ASSOC );
echo json_encode( $data );

答案 1 :(得分:2)

我用这个:     

    $json = array();

    if(mysqli_num_rows($result)){
        while($row=mysqli_fetch_assoc($result)){
                $json[]=$row;
        }
    }
    mysqli_close($mysqli);
    echo json_encode($json);

?>

我得到这样的东西

[ { “ID”: “2”, “usuario”: “zeldafranco”, “密码”: “笑”},{ “ID”: “3”, “usuario”: “弗朗”, “密码”: “弗朗” },{ “ID”: “4”, “usuario”: “peteko”, “密码”: “sanpeteko”},{ “ID”: “5”, “usuario”: “prueba”, “密码”:” prueba “},{” ID “:” 6" , “usuario”: “测试”, “密码”: “测试”}, { “ID”: “7”, “usuario”: “pibe”, “密码”: “HOLA”}, {“id”:“8”,“usuario”:“que ase”,“password”:“que ase”},{“id”:“9”,“usuario”:“trt”,“password”:“ TRT“}, { “ID”: “10”, “usuario”: “TYT”, “密码”: “TYT”} ]

答案 2 :(得分:-2)

$arrUsers = array();

$fetch = mysql_query("SELECT * FROM users"); 

while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {



 $arrUsers['id'] = $row['name'];
    $arrUsers['col1'] = $row['col1'];
    $arrUsers['col2'] = $row['col2'];

    array_push($arrUsers,$row_array);

}

echo json_encode($arrUsers);