从MYSQL数据库创建JSON字符串

时间:2013-11-07 00:13:51

标签: php mysql json

我试图以json字符串的形式从MySQL数据库中获取数据。

我读到了这个答案:JSON encode MySQL results

但这只限于一张桌子。如果我想从多个表中获取数据(来自userDetails的名称,从UserPurchases购买数据等),该怎么办?如何创建自定义字符串,从多个表中获取数据并仅从单个表创建json字符串?

 $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'];

现在,如何从单独的表中使用这些数据来构建单个json。 该字符串应具有thingName,thingOwnerId,thingDescription,thingOwnerName。

3 个答案:

答案 0 :(得分:1)

您还可以在PHP中创建一个类,将数据库值设置为此类并编码为JSON,例如:

<?php

class MyCustomJson
{
    public $userId;
    public $thingId;
    //and go on...
}

//set db values to this class
$myCustomJson = new MyCustomJson();
//..read data from User table and set table values to your custom object
$myCustomJson->userId = $row["id"];
//..read data from Thing table and set table values to your custom object
$myCustomJson->thingId = $row["id"];

//and encode your custom object to json
echo json_encode($myCustomJson);
?>

答案 1 :(得分:1)

从数组中的查询中收集所需数据,然后以JSON编码格式将该数组输出到浏览器。请记住在任何输出之前设置Content-Type: application/json标题。

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 :(得分:0)

如果它们是不同的查询,您可以合并结果并对该数组进行编码,如下所示:

$merged = array();

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

// 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 ( );
$merged['user'] = $rslt;

echo json_encode($merged);