2

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.

4

3 回答 3

1

you can also create a class in PHP, set database values to this class and encode to JSON, eg.:

<?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);
?>
于 2013-11-07T00:20:43.837 回答
1

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);
于 2013-11-07T09:48:18.047 回答
0

If they are different queries, you can merge the results and encode that array like this:

$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);
于 2013-11-07T00:17:35.933 回答