Nrc
Nrc

Reputation: 9787

Conditional in select count

I count the number of comments of each post. And it works:

$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);

But I prefer to show the number of comments only if there is any comments. But I have problems with the conditional.

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

}

How can I say that If there is comments show the number. If there is 0 comments don't show anything ( I don't want it to show "there is 0 comments")

Upvotes: 0

Views: 91

Answers (2)

Teena Thomas
Teena Thomas

Reputation: 5239

Try:

$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...
 }

Upvotes: 2

Adam
Adam

Reputation: 1264

Try:

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

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

Upvotes: 1

Related Questions