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条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测