php 如果返回 0 行,则 MySQL 返回结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5044790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:37:46  来源:igfitidea点击:

MySQL return result if 0 rows returned

phpmysql

提问by Tom

I have this PHP code:

我有这个 PHP 代码:

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

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"

如果没有来自该用户的消息,我如何让它返回一个值?目前是什么都不显示。但我希望它显示“发布的消息:0”

Any ideas?

有任何想法吗?

回答by shamittomar

Check the number of results returned in result using mysql_num_rows.

使用 来检查 result 中返回的结果数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 />";

回答by mellamokb

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

回答by eykanal

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

替换$row['COUNT(message)']三级运算符

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

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

这基本上是一个压缩if... else...语句。