get number of rows with pdo(使用 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];
echo 好像返回的是记录的 ID 值,而不是查询返回的记录数?
the echo seems to be returning the ID value of the record, not the number of records returned by the query?
对此有何想法或解释?
推荐答案
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 获取行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 pdo 获取行数
基础教程推荐
- 无法解决整理冲突 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 在 SQL 中连接多个表 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
