1

我有一个包含多行的表,我想用 json 对所有行进行编码。

我一直在寻找其他问题和解决方案,我尝试了很多不同的方法,但 json_encode 仍然返回 null

<?php
    $mysqli = new mysqli('localhost', 'root', 'password', 'testBasParmak');

    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    $sth = mysql_query("SELECT * FROM pictures");
    $rows = array();
    while($r = mysql_fetch_assoc($sth)) {
        $rows[] = $r;
    }
    print json_encode($rows); 

    $error = json_last_error();
    print  $error;

$mysqli->close();

?>

终端的输出是

[]0

如果我试试这个

$sth = mysql_query("SELECT * FROM pictures");
    $rows = array("id" => $id,"name" => $name,"description" => $description,"url" => $url,"users_id" => $users_id,"users_id" => $users_id,"totalvoteup" => $totalvoteup,"totalvotedown" => $totalvotedown,"totalvoteneutral" => $totalvoteneutral);
    while($r = mysql_fetch_assoc($sth)) {
        $row[] = $r;
    }
    print json_encode($rows); 

    $error = json_last_error();
    print  $error;

终端的输出是

{"id":null,"name":null,"description":null,"url":null,"users_id":null,"totalvoteup":null,"totalvotedown":null,"totalvoteneutral":null}0

也许它没有发送正确的查询?

4

2 回答 2

3

$row[] = $r;

应该

$rows[] = $r;

于 2012-07-02T07:50:20.300 回答
0

最后我找到了答案,我的数据库连接是 mysqli 但我的查询SELECT *是 mysql 我需要更改的只是 mysql 命令到 mysqli

$sth = $mysqli->query("SELECT * FROM pictures");
    $rows = array();
    while($r = mysqli_fetch_assoc($sth)) {
        $rows[]=$r;
    }
    print json_encode($rows); 

给出正确的输出

["id":"2","name":"Jess","description":"who","url":"www","users_id":"705735067","totalvoteup":"0","totalvotedown":"0","totalvoteneutral":"0"},{"id":"3","name":"Jess","description":"who","url":"www","users_id":"705735067","totalvoteup":"0","totalvotedown":"0","totalvoteneutral":"0"},{"id":"4","name":"Jess","description":"who","url":"www","users_id":"705735067","totalvoteup":"0","totalvotedown":"0","totalvoteneutral":"0"}]
于 2012-07-02T08:28:17.413 回答