-4

How can I return the number of counted rows with PDO?

This is my code:

$n=$dbh->prepare("SELECT count(*) FROM users_notifications WHERE userid=0 OR userid=:userid");
$n->bindParam(":userid",$userdata['id']);
$n->execute();
$notifications = count($n);

This returns just 1. Although there are 2 results when I run the query in the database: SELECT count(*) FROM users_notifications WHERE userid=0 OR userid=:userid

oliverbj
  • 5,771
  • 27
  • 83
  • 178
  • Have a look at this question: http://stackoverflow.com/questions/883365/row-count-with-pdo – Bono Sep 13 '14 at 10:13

1 Answers1

0

The count SQL function is an aggregate function that returns one row with the number of rows matching the where clause.

PHP's count returns the number of rows in a result set, which, as illustrated in the previous paragraph, should be one. Instead, you should retrieve the value of the result column. E.g.:

$n=$dbh->prepare("SELECT count(*) as c FROM users_notifications WHERE userid=0 OR userid=:userid");
$n->bindParam(":userid",$userdata['id']);
$n->execute();
$result = $n->fetch(PDO::FETCH_ASSOC);
$notifications = $result['c'];
Mureinik
  • 297,002
  • 52
  • 306
  • 350