doudun5009 2016-03-02 08:43
浏览 59
已采纳

将PHP MySQL查询响应编码为JSON问题

I am basically trying to call a MySQL Query and get the response from the Server, which I have done and it works. Now I need to encode the response as a JSON Array (Each Row as a JSON Object and add them to a JSON Array)

My Code:

foreach ($db->query('SELECT * from mydb.UserTable') as $sqlresp) {
        $rows = array();
        while($r = mysqli_fetch_assoc($sqlresp)) {
              $rows['users'][] = $r;
        }
        print json_encode($rows);
}

The above code gives me this error:

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, array

It points to this line:

while($r = mysqli_fetch_assoc($sqlresp)) {

JSON Object I need in the JSON Array:

Roughly this would be the structure..

user
{
     name: "john",
     picture: "http://...."
     details {
          email: "email@gmail.com",
          telephone: "3456..."
     }
}

*Column names of the table are the same as the Object Property names (e.g.: name, picture, etc)

What's wrong with my code and how do I properly encode my query response's rows as a JSON Array, folks?

EDIT:

I need the Array because I need to send this array to a Javascript function. So I need it in JSON Array Format

  • 写回答

2条回答 默认 最新

  • dongqian9013 2016-03-02 09:07
    关注

    what is $db, if it is mysqli connection resource, then it will support

    IMO,

    $sqlresp=$db->query('SELECT * from mydb.UserTable');
    

    it is custom library and it returns array

    so you can use

    echo json_encode( $sqlresp );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?