count()函数不返回行数

bwleehnv  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(492)

我在一个博客系统网站上工作。在这个博客系统中,我有两个表。一个叫做 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。
那么这个代码怎么了,你能帮我一下吗!

kqlmhetl

kqlmhetl1#

"SELECT COUNT() FROM blogs WHERE blog_category = '$id'"

将返回一行。所以$numcat变为1。
您需要获取查询结果并从count()获取值

function num_cats($id){
    $num_cats = "SELECT COUNT(*) AS count FROM blogs WHERE blog_category = '$id'";
    if ($result = mysqli_query($GLOBALS['con2'], $num_cats)) {
        $row = mysqli_fetch_assoc($result);
        return $row['count'];
    } else {
        die(mysqli_error($GLOBALS['con2']));
    }
}
dpiehjr4

dpiehjr42#

COUNT 将给出 blog_category 在你的数据库里。所以在结果中只有一个类别计数的代码。
但你打电话来 mysqli_num_rows 又来了。所以,结果总是1。
把它拿走 mysqli_num_rows($run_num); 并用结果列名称更新查询,

SELECT COUNT(*) AS `total` FROM blogs WHERE blog_category = '$id'

那就打电话

$row = mysqli_fetch_object($run_num);
$numCat = $row->total;
w8f9ii69

w8f9ii693#

使用join提高性能

$sql = "Select table_id,cat_title,bc.cat_id,count(b.category_id) as total_post from blog b inner join blog_category bc on b.blog_category_id=bc.blog_category_id group by b.category_id";
$result = mysqli_query($GLOBALS['con2'],$sql);
while($cat = $result->mysqli_fetch_row()){
echo "
   <tr>
    <td>".$cat['table_id']."</td>
    <td>".$cat['cat_title']."</td>
    <td>".$cat['cat_id']."</td>
    <td>".$cat['total_post']."</td>
    <td></td>
 </tr>";
}

相关问题