繁体   English   中英

如何在代表另一个类别的表中显示来自 1 个类别 (tbl_category) 的项目标题?

[英]How do I display item title from 1 category (tbl_category) in a table that represents another category?

我有 2 张桌子tbl_categorytbl_food

我通过将category_id添加到tbl_category将项目从tbl_food排序到tbl_food ,其中 tbl_food 中的category_idtbl_food中的id tbl_category

但是如何从tbl_category获取标题并将其显示在代表tbl_food项目的表中?

<?php
    //query to get all admin from dtb 
    $sql = "SELECT * FROM tbl_food";
    //Exectue the query
    $res = mysqli_query($conn, $sql);
    //check if executed
    if($res==TRUE)
    {
    //count rows to check wether we have data
        $count = mysqli_num_rows($res); //get all rows in dtb

        $sn=1; //create a variable and assign the value
        //check numb of rows
        if($count>0)
        {
            //there is data
            while($rows=mysqli_fetch_assoc($res))
            {
                //using while loop to get data from dtb

                //get individual data
                $id=$rows['id'];
                $title=$rows['title'];
                $description=$rows['description'];
                $price=$rows['price'];
                $active=$rows['active'];
                $category_id=$rows['category_id'];

                
                //display values in table
                ?>
                <tr>
                        <td><?php echo $sn++; ?></td>
                        <td><?php echo $title; ?></td>
                        <td><?php echo $description; ?></td>
                        <td><?php echo $price; ?> kn</td>
                        <td><?php echo $active; ?></td>
                        <td><?php echo $category_id; ?></td> 
</tr>
                <?php
            
    }}
    else{
        ?>
        <tr colspan="4">
            <td class="error">No categories added</td>
    </tr>
    <?php  
    }
}
  ?>

我认为您首先需要通过添加JOIN以通过category_idtbl_food加入tbl_category来编辑查询,如下所示:

$sql = "SELECT food.*, category.title FROM tbl_food AS food INNER JOIN tbl_category AS category ON category.id=food.category_id";

其次,您似乎在迭代查询结果时犯了错误。 mysqli_fetch_assoc($res)返回一个关联数组,所以它必须是这样的:

$rows = mysqli_fetch_assoc($res)
foreach($rows as $row){
 $id=$row['id'];
 $title=$row['title'];
 $description=$row['description'];
 $price=$row['price'];
 $active=$row['active'];
 $category_id=$row['category_id'];
 //Doing stuff
}

您必须从 tbl_category 获取标题的方法 1- JOIN 方法:上面已经提到 2- 条件方法:

$sql = "SELECT tbl_food.*, tbl_category.title FROM tbl_food,tbl_category WHERE tbl_category.id=tbl_food.category_id";

foreach($sql as $row){

$id=$row['id'];
 $title=$row['title'];
 $description=$row['description'];
 $price=$row['price'];
 $active=$row['active'];
 $category_id=$row['category_id'];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM