dream752614590 2013-11-07 00:13
浏览 109
已采纳

从MYSQL数据库创建JSON字符串

I am trying to get data from MySQL database in form of a json string.

I read this answer: JSON encode MySQL results

But this is limited to a single table. What if I want to get data from multiple tables (name from userDetails, purchase data from UserPurchases etc)? How can I create a custom string, getting data from multiple tables and creating a json string like it’s from a single table only?

 $query = "SELECT * FROM `thing` WHERE `id` = :thingId";
    $stmt = $dbh->prepare ( $query );
    $stmt->bindParam ( ":thingId" , $_GET['thingId']  );
    $stmt->execute ( );
    $rslt  =  $stmt->fetch ( );
    $thingName  = $rslt['name'];
    $thingOwnerId = $rslt['userId'];
    $thingDescription = $rslt['thingDescription'];

// Getting the thing owner details
    $query = "SELECT * from `user` WHERE ( `id` = :id ) ";    
    $stmt = $dbh->prepare( $query );
    $stmt->bindParam ( ":id" , $thingOwnerId );
    $stmt->execute(  );
    $rslt = $stmt->fetch ( );
    $thingOwnerName = $rslt['firstName']." ".$rslt['lastName'];

Now, how to make a single json strong out of this data from separate tables. The string should have the thingName,thingOwnerId, thingDescription, thingOwnerName.

  • 写回答

3条回答 默认 最新

  • dongyanling9248 2013-11-07 09:48
    关注

    Collect the required data from your queries in an array, then output that array in a JSON encoded format to the browser. Remember to set the Content-Type: application/json header before any output.

    PHP

    //collect your data in an array
    $data=array(
        'name'=>$thingOwnerName,
        'description'=>$thingDescription,
        'otherField'=>$someValue
        ...
    );
    
    //send JSON header to browser
    header('Content-Type: application/json');
    
    //echo JSON encoded data
    echo json_encode($data);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败