PHP - 返回计数(*)结果

时间:2014-09-13 10:10:59

标签: php mysql sql pdo

如何使用PDO返回计算行数

这是我的代码:

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

这只返回1.虽然在数据库中运行查询时有 2 结果:SELECT count(*) FROM users_notifications WHERE userid=0 OR userid=:userid

1 个答案:

答案 0 :(得分:0)

count SQL函数是一个聚合函数,它返回一行,其中包含与where子句匹配的行数。

PHP' s count返回结果集中的行数,如前一段所示,它应为1。相反,您应该检索结果的值。 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'];