1

我正在尝试遍历 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) . ", ";
    }

?>
4

3 回答 3

14
$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 );
于 2012-08-09T22:12:05.230 回答
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","password":"lol"},{"id":"3","usuario":"franco","password":"franco "},{"id":"4","usuario":"peteko","password":"sanpeteko"},{"id":"5","usuario":"prueba","password": "prueba"},{"id":"6","usuario":"test","password":"test"}, {"id":"7","usuario":"pibe","password ":"hola"}, {"id":"8","usuario":"que ase","password":"que ase"},{"id":"9","usuario":"trt “,“密码”:"trt"}, {"id":"10","usuario":"tyt","password":"tyt"} ]

于 2014-01-27T17:38:49.723 回答
-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);
于 2012-08-09T22:15:42.603 回答