-3

下面是计数评论的脚本。这行得通,但现在我想当评论 0 时,它只显示评论,而不是 0 评论。

有什么建议么 ?

<?php
            include "con_config_hapshout.php";

            $query3 = "SELECT COUNT(comment) FROM comment WHERE msg_id='$id'";
            $result3 = mysql_query($query3);

            while($total = mysql_fetch_array($result3)){
                            echo "$total['COUNT(comment)'] comment";
                        }

            ?>
4

3 回答 3

2
<?php
        include "con_config_hapshout.php";

        $query3 = "SELECT IF(COUNT(comment) = 0, '', COUNT(comment)) AS comment_count
                   FROM comment WHERE msg_id='$id'";
        $result3 = mysql_query($query3);

        while($total = mysql_fetch_array($result3)){
                        echo "$total['comment_count'] comment";
                    }

?>
于 2012-09-03T06:30:05.430 回答
1

按列名对结果进行分组。

SELECT COUNT(comment) 
FROM comment 
WHERE msg_id='$id'
GROUP BY comment

SQLFiddle 演示

于 2012-09-03T06:33:06.070 回答
0

您误用了 PHP 字符串 - 双引号字符串中的数组键引用不应被引用,除非您使用{}语法。

echo "{$total['COUNT(comment)']} comment";
      ^---                     ^--

或者更好的是,在查询中为计数设置别名,这样您以后就不必在 PHP 中使用如此丑陋的数组键:

SELECT COUNT(comment) AS cnt ...

and

echo $total['cnt'];
于 2012-09-03T06:32:44.057 回答