使用pdo获取行数 [英] get number of rows with pdo

查看:230
本文介绍了使用pdo获取行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的pdo准备查询:

I have a simple pdo prepared query:

$result = $db->prepare("select id, course from coursescompleted where person=:p"); 
$result ->bindParam(':p', $q, PDO::PARAM_INT);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
echo $rows[0];

回声似乎正在返回记录的ID值,而不是查询返回的记录数?

the echo seems to be returning the ID value of the record, not the number of records returned by the query?

对此有任何想法或解释吗?

any idea or explanation for this?

推荐答案

PDO :: FETCH_NUM: 返回从结果列返回的,按列号索引的数组,从第0列开始

PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0

您根本不会获取行数.

SELECT COUNT(*) FROM coursescompleted where person=:p

此查询将返回$rows[0];

请参阅@ray的答案.对于InnoDB,使用count(id)优于count(*).

Please see @ray's answer. using count(id) is better than count(*) for InnoDB.

您可以通过以下方式从先前的查询中获取行数.

You could get row-count in the following manner, from your earlier query.

$row_count = $result->rowCount();

但要警告:

如果关联的PDOStatement执行的最后一条SQL语句是 SELECT语句,某些数据库可能返回行数 该语句返回的值.但是,不能保证此行为 用于所有数据库,不应该依赖于便携式 应用程序.

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

文档

这篇关于使用pdo获取行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆