这是我从两个表(运输信息和订单)获取数据后得出的代码。我得到的数据之一是product_id。其中product_id是第三个表名product的主键。我想从第三个表产品中检索产品标题和产品价格。我应该如何写我的sql?下面展示了从2个表中检索数据的sql。
<?php
include ('classes/functions.php');
if(isset($_POST['user_id'])){
$user_id = $_POST['user_id'];
$check_receipt = "select si.shipping_name,
si.shipping_address,
si.shipping_contact,
si.shipping_email,
o.order_date,
o.trx_id,
o.tracking_num,
o.quantity,
o.product_id
from shipping_infos si
inner join orders o
on si.user_id = o.user_id
where si.user_id='".$user_id."';";
$run_receipt_checking = mysqli_query($con, $check_receipt);
$result = array();
while($row = mysqli_fetch_array($run_receipt_checking)){
array_push($result,
array(
'shipping_name'=>$row[0],
'shipping_address'=>$row[1],
'shipping_contact'=>$row[2],
'shipping_email'=>$row[3],
'order_date'=>$row[4],
'trx_id'=>$row[5],
'tracking_num'=>$row[6],
'quantity'=>$row[7],
'product_id'=>$row[8]
));
}
echo json_encode(array("result"=>$result));
}
?>
您可以使用
JOIN
组合三张桌子
尝试像下面这样
<?php
include ('classes/functions.php');
if(isset($_POST['user_id'])){
$user_id = $_POST['user_id'];
$check_receipt = "select si.shipping_name,
si.shipping_address,
si.shipping_contact,
si.shipping_email,
o.order_date,
o.trx_id,
o.tracking_num,
o.quantity,
o.product_id
from shipping_infos si
inner join orders o
on si.user_id = o.user_id
inner join products p on p.product_id = o.product_id
where si.user_id='".$user_id."';";
$run_receipt_checking = mysqli_query($con, $check_receipt);
$result = array();
while($row = mysqli_fetch_array($run_receipt_checking)){
array_push($result,
array(
'shipping_name'=>$row[0],
'shipping_address'=>$row[1],
'shipping_contact'=>$row[2],
'shipping_email'=>$row[3],
'order_date'=>$row[4],
'trx_id'=>$row[5],
'tracking_num'=>$row[6],
'quantity'=>$row[7],
'product_id'=>$row[8]
));
}
echo json_encode(array("result"=>$result));
}