Php 从MYSQL数据库创建JSON字符串
我试图以json字符串的形式从MySQL数据库获取数据 我读到这个答案: 但这仅限于一张桌子。如果我想从多个表中获取数据(userDetails中的name、UserPurchases中的purchase数据等),该怎么办?如何创建自定义字符串,从多个表中获取数据,并像只从一个表中创建json字符串一样创建json字符串Php 从MYSQL数据库创建JSON字符串,php,mysql,json,Php,Mysql,Json,我试图以json字符串的形式从MySQL数据库获取数据 我读到这个答案: 但这仅限于一张桌子。如果我想从多个表中获取数据(userDetails中的name、UserPurchases中的purchase数据等),该怎么办?如何创建自定义字符串,从多个表中获取数据,并像只从一个表中创建json字符串一样创建json字符串 $query = "SELECT * FROM `thing` WHERE `id` = :thingId"; $stmt = $dbh->prepare (
$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。如果它们是不同的查询,您可以合并结果并对该数组进行如下编码:
$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);
您还可以在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);
?>
从数组中的查询中收集所需数据,然后以JSON编码格式将该数组输出到浏览器。记住在任何输出之前设置
内容类型:application/json
头
PHP
你能告诉我如何返回json格式的数据吗。不仅仅是echo,jSON格式?当您执行jSON_encode()时,它已经返回一个jSON。你可以做$var=json\u编码($something);而是使用echo。没关系吧?我想没有。我想知道twitter的功能。echo json_编码($something);应该像这个twitter示例那样打印json。如果没有打印json,那么在此之前您就出了问题。你能用实际的代码更新你的问题来解决吗?我正在得到结果。只是我在firefox中查看json数据的插件没有将其识别为json。也许这个插件有问题。谢谢<代码>内容类型帮助!
//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);