我在一个博客系统网站上工作。在这个博客系统中,我有两个表。一个叫做 blogs
它只包含博客的信息(如博客标题、博客作者、博客类别)。
另一个叫做 categories
它只包含博客文章的博客类别名称。
现在我制作了一个页面,用户可以在其中查看博客类别和该自定义类别名称中的博客文章数。
下面是它的样子:
这就是背后的代码:
foreach($catShow as $cat){
echo "
<tr>
<td>".$cat['table_id']."</td>
<td>".$cat['cat_title']."</td>
<td>".$cat['cat_id']."</td>
<td>".num_cats($cat['cat_id'])."</td>
<td></td>
</tr>";
}
所以函数 num_cats()
基本上是统计博客文章的数量 blogs
具有相同博客类别id的表( cat_id
):
function num_cats($id){
$num_cats = "SELECT COUNT(*) FROM blogs WHERE blog_category = '$id'";
$run_num = mysqli_query($GLOBALS['con2'],$num_cats);
$return = '';
if (!$run_num) {
die(mysqli_error($GLOBALS['con2']));
}
$numCat = mysqli_num_rows($run_num);
$return .= "
$numCat
";
return $return;
}
但现在的问题是,结果是不正确的。我的意思是,表中只显示了一个结果为每个类别,但其中有些人有一个以上的项目在同一时间 blogs
table。
那么这个代码怎么了,你能帮我一下吗!
3条答案
按热度按时间kqlmhetl1#
将返回一行。所以$numcat变为1。
您需要获取查询结果并从count()获取值
dpiehjr42#
COUNT
将给出blog_category
在你的数据库里。所以在结果中只有一个类别计数的代码。但你打电话来
mysqli_num_rows
又来了。所以,结果总是1。把它拿走
mysqli_num_rows($run_num);
并用结果列名称更新查询,那就打电话
w8f9ii693#
使用join提高性能