下面的PHP代码适用于从wamp服务器查询数据并返回要在XML页面中使用的JSON对象。
JSON数组应包含该项目的描述,价格,数量和图像。
如何回显包含从$ row2和$ row3中检索到的数据的JSON?
谢谢
<?php
session_start();
if(isset($_SESSION["userID"]))
{
//echo $_SESSION["userID"];
?>
<body>
<?php
include("connection_manager.php");
$query1="Select * from cart where userid='".$_SESSION["userID"]."'";
$result1=mysql_query($query1);
$row1=mysql_fetch_array($result1);
$query2="Select * from store where itemid='".$row1['itemid']."'";
$result2=mysql_query($query2);
$row2=mysql_fetch_array($result2);
$query3="Select * from photos where itemID='".$row1['itemid']."'";
$result3=mysql_query($query3);
$row3=mysql_fetch_array($result3);
?>
答案 0 :(得分:2)
将关联数组输出为JSON,使用json_encode
输出描述$ row2的JSON:
echo json_encode($row2);
您还需要将Content-Type标头设置为application / json。
答案 1 :(得分:0)
我会使用表连接将其简化为返回单个数组的单个查询,然后在该数组上使用json_encode(请参阅http://www.php.net/manual/en/function.json-encode.php)
可能类似以下内容:
$userId = $_SESSION['userID'];
$query = "SELECT store.*, photos.*
FROM cart
INNER JOIN store ON store.itemid = cart.itemid
INNER JOIN photos ON photos.itemid = cart.itemid
WHERE cart.userid='$userId'";
echo json_encode(mysql_fetch_array(mysql_query($query)));
话虽如此,请参阅这篇文章,了解为何不使用mysql_函数: Why shouldn't I use mysql_* functions in PHP?
- 编辑 - 以下是使用SQLite的示例;您可以将其更改为匹配您要使用的数据库:
$db = new SQLite3("db.db");
$query = "SELECT store.description, store.price, store.quantity, photos.photo_url
FROM cart
INNER JOIN store ON store.item_id = cart.item_id
INNER JOIN photos ON photos.item_id = cart.item_id
WHERE cart.user_id=1;";
$results = $db->query($query);
$full_array = array();
while ($row = $results->fetchArray())
{
$full_array[] = $row;
}
echo json_encode($full_array);
输出:
[
{
"0": "a",
"1": 1,
"2": 1,
"3": "/images/photo_1.jpg",
"description": "a",
"price": 1,
"quantity": 1,
"photo_url": "/images/photo_1.jpg"
},
{
"0": "b",
"1": 2,
"2": 2,
"3": "/images/photo_2.jpg",
"description": "b",
"price": 2,
"quantity": 2,
"photo_url": "/images/photo_2.jpg"
},
{
"0": "c",
"1": 3,
"2": 3,
"3": "/images/photo_3.jpg",
"description": "c",
"price": 3,
"quantity": 3,
"photo_url": "/images/photo_3.jpg"
},
{
"0": "d",
"1": 4,
"2": 4,
"3": "/images/photo_4.jpg",
"description": "d",
"price": 4,
"quantity": 4,
"photo_url": "/images/photo_4.jpg"
},
{
"0": "e",
"1": 5,
"2": 5,
"3": "/images/photo_5.jpg",
"description": "e",
"price": 5,
"quantity": 5,
"photo_url": "/images/photo_5.jpg"
}
]