使用选择计数时隐藏0

时间:2012-09-03 06:28:42

标签: php mysql

下面的

是计数评论的脚本。这有效,但现在我想要评论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";
                        }

            ?>

3 个答案:

答案 0 :(得分: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";
                    }

?>

答案 1 :(得分:1)

按列名称对结果进行分组。

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

SQLFiddle Demo

答案 2 :(得分:0)

你错误地使用PHP字符串 - 双引号字符串中的数组键引用不应该引用,除非你使用{}语法。

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

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

SELECT COUNT(comment) AS cnt ...

and

echo $total['cnt'];