php - 如何使用表之间的关系在 php 和 mysql 中显示数据
问题描述
我建立了一个关于网上商店的项目,管理仪表板中有一个页面,显示来自用户的订单信息..有很多表
- 有Order.php类的订单表。
- 有Product.php类的产品表。
- 有OrderDetails.php类的orderdetails表。在这个表中有id,order_id,product_id。
每件事都运行良好,我无法显示 $product['name'] 和 $product['price'] 因为 $orderDet 返回空值,我不知道如何从 orderdetails 表中获取 id 以使用它获取产品表数据。
- OrderDetails.php 类中的 getOne 函数
//get one
public function getOne($id){
$query="SELECT * FROM `orderdetails`
WHERE `id` = '".$id."'";
$result=$this->connect()->query($query);
$orderdetails=null;
if($result->num_rows == 1)
{
$orderdetails = $result->fetch_assoc();
}
return $orderdetails;
}
- Orders.php,我在其中显示客户的信息和他们为管理员购买的订单
<?php
session_start();
require_once 'classes/product.php';
require_once 'classes/Order.php';
require_once 'classes/Orderdetails.php';
require_once 'classes/Category.php';
require_once 'inc/header.php';
$ord=new Order;
$ordDet=new OrderDetails;
$prod=new Product;
$orders=$ord->getAll();
if(!isset($_SESSION['id']))
{
header('location:Login.php');
die();
}
?>
<div class="container">
<div class="row">
<div class="col-lg-12">
<table class="table">
<thead>
<tr>
<th>Customer Name</th>
<th>Customer Email</th>
<th>Customer Phone</th>
<th>Customer Address</th>
<th>Product Name</th>
<th>Product Price</th>
</tr>
</thead>
**the problem is here**
<?php
foreach($orders as $order)
{
$orderDetails=$ordDet->getOne($order['order_id']);
//var_dump($orderDetails);
$product=$prod->getOne($orderDetails['product_id']);
?>
<tbody>
<tr>
<td scope="row"><?php echo $order['customerName']; ?></td>
<td><?php echo $order['customerEmail']; ?></td>
<td><?php echo $order['customerPhone']; ?></td>
<td><?php echo $order['customerAddress']; ?></td>
<td><?php echo $product['name']; ?></td>
<td><?php echo $product['price']; ?></td>
</tr>
</tbody>
<?php } ?>
</table>
</div>
</div>
</div>
<?php require_once 'inc/footer.php';?>
解决方案
试试下面的。
$query = "SELECT * FROM `orderdetails` WHERE `id` != ''";
// or $query = "SELECT * FROM `orderdetails` WHERE `id` != 0";
$result = $con->query($query);
while($row = $result->fetch_assoc()){
$id = $row["id"];
echo "<h3>id is now $id</id>";
}
推荐阅读
- c# - 使用 Google Cloud Vision 检测 PDF/TIFF 文件中的文本
- javascript - 如何在 draw.io 中创建新图像并从我的网站中保存它的数据库?
- java - Spring Boot 在迁移到 JDK 11 后由于 Hibernate 错误而失败
- kentico - 如何获取指定用户的折扣 SKU 价格?
- asp.net-mvc - 使用 ASP.NET MVC 处理全局和 HTTP 异常
- node.js - 使用 axios 处理来自异步等待语法的错误
- php - Laravel 数据库限制
- c# - 如何从属性选项卡推断 C# 属性名称,以及如何操作它们?
- ios - iOS Admob 插页式广告冻结并变得无响应
- android - 如何在 recyclerview 适配器的 html 内容中显示图像?