条件选择计数

时间:2012-11-13 14:23:07

标签: php select

我计算每篇文章的评论数量。它有效:

$numComments = mysql_query("SELECT COUNT(id_post) FROM comments WHERE id_post = '". $row["id"]."' ");  
// it works if I do this: echo mysql_result($numComents,0);

但是我更喜欢只在有任何评论的情况下显示评论数量。但我有条件的问题。

if ($numComments > 0){
    echo mysql_result($numComments,0); 
}else{

}

我该怎么说如果有评论显示该号码。如果有0条评论没有显示任何内容(我不希望它显示“有0条评论”)

2 个答案:

答案 0 :(得分:2)

尝试:

$result = mysql_query("SELECT COUNT(id_post) FROM comments WHERE id_post = '". $row["id"]."' "); 
$numComments = mysql_result($result,0);
if ( $numComments  > 0) {
 echo $numComments ; 
 } else {
   //do something...
 }

答案 1 :(得分:1)

尝试:

$number_of_rows = mysql_fetch_row($numComments)[0];

echo $number_of_rows > 0 ? $number_of_rows : '';