简体   繁体   中英

Count(id) mysql - show 0 if no results?

I want to count(id) if an user has new chat messages.

My problem is if there is no message it doesn't give me 0 as a result. What is wrong?

$stmt = $mysqli->prepare("SELECT count(id) FROM chat WHERE `to`=? and recd='0' group by `from`");
$stmt->bind_param('s', $user);
$stmt->execute();
$stmt->bind_result($chatcont);
$stmt->fetch();
$stmt->close();

php:

echo "($chatcont)";

if no message I have:

()

I want to show 0 inside this.

Use $stmt->num_rows to return the number of rows in your result. If that is 0 then echo 0 else echo $chatcont

Yet you don't need to use bind_result in PDO statements. Please, avoid unnecessary actions. Just get your data and use it anywhere.

$stmt = $mysqli->prepare("SELECT count(id) as count FROM chat WHERE `to`=? and recd='0' group by `from`");
$stmt->execute(array($user));
$chatcont = $stmt->fetch();

echo $chatcont['count'];

Here, you will get either count or 0

That's one of questions that, being wrongly put, make people writing wrong answers all around.

Using SQL properly , count() will always return a number.

It's SQL which is wrong. While accepted answer is essentially wrong and should never be used, as it has been answered here thousands times already , all in vain.

SELECT count(id) FROM chat WHERE `to`=? and recd='0'

is the right answer to get the number of unread messages.

To get the number of senders is another question . That can could have been answered with SQL as well. If were ever asked .

SELECT count(distinct `from`) FROM chat WHERE `to`=? and recd='0'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM