开发者

MySQL return result if 0 rows returned

I have this PHP code:

$query = "开发者_JAVA技巧SELECT name, COUNT(message) FROM guestbook_message WHERE name='".$req_user_info['username']."' GROUP BY name"; 

$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result))
{
    echo "Messages posted: ". $row['COUNT(message)'] ."";
    echo "<br />";
}

Which will show the amount of comments a user has posted.

How do I make it return a value if there is no messages posted from that user? Currently is displays nothing at all. But I want it to show "Messages posted: 0"

Any ideas?


Check the number of results returned in result using mysql_num_rows.

$query = "SELECT name, COUNT(message) FROM guestbook_message WHERE name='".$req_user_info['username']."' GROUP BY name"; 

$result = mysql_query($query) or die(mysql_error());

if(mysql_num_rows($result) > 0)
    while($row = mysql_fetch_array($result))
    {
       echo "Messages posted: ". $row['COUNT(message)'] ."";
       echo "<br />";
    }
else
    echo "NO Messages posted. <br />";


if ($row = mysql_fetch_array($result)) {
    echo "Messages posted: ". $row['COUNT(message)'] . "";
    echo "<br />";
}
else {
    echo "Messages posted: 0";
    echo "<br />";
}


Replace $row['COUNT(message)'] with the tertiary operator:

( $row['COUNT(message)'] > 0 ? $row['COUNT(message)'] : 0 )

This is basically a compacted if... else... statement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜