0

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.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
RGS
  • 4,062
  • 4
  • 31
  • 67
  • 1
    I believe that `NULL` output is coming instead of `0` in the count because of the `GROUP BY` command. When there are `0 rows` in the output, the GROUP BY command cannot GROUP anything, thus producing a NULL structure. – Anshuman Chatterjee Sep 18 '15 at 12:27
  • oh, you are right! group by is the problem here... should I use num rows instead? because I need to count messages by senders, not by the real number of messages... – RGS Sep 18 '15 at 12:32

3 Answers3

2

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

AgeDeO
  • 3,137
  • 2
  • 25
  • 57
  • thank you! the problem in count is group by as Anshuman Chatterjee said! I think the solution is num_rows indeed... thanks – RGS Sep 18 '15 at 12:34
0

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

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'
Community
  • 1
  • 1
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345