[英]How do I display item title from 1 category (tbl_category) in a table that represents another category?
我有 2 张桌子tbl_category
和tbl_food
。
我通过将category_id
添加到tbl_category
将项目从tbl_food
排序到tbl_food
,其中 tbl_food 中的category_id
与tbl_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_id
将tbl_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.