首页 > 解决方案 > 如何使用表之间的关系在 php 和 mysql 中显示数据

问题描述

我建立了一个关于网上商店的项目,管理仪表板中有一个页面,显示来自用户的订单信息..有很多表

每件事都运行良好,我无法显示 $product['name'] 和 $product['price'] 因为 $orderDet 返回空值,我不知道如何从 orderdetails 表中获取 id 以使用它获取产品表数据


//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;
}
<?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';?>

那是我制作 var_dump($orderDetails) 时的图像

标签: phpmysql

解决方案


试试下面的。

$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>";
}


推荐阅读