>  기사  >  백엔드 개발  >  PDO连接数据库时怎么获取结果集的数目

PDO连接数据库时怎么获取结果集的数目

WBOY
WBOY원래의
2016-06-13 13:16:151100검색

PDO连接数据库时如何获取结果集的数目
查了下手册 好像没有发现PDO中类似于mysql_num_rows这样的函数用于计算返回结果集的数目
rowCount是返回SQL语句执行后影响的行数。。。

------解决方案--------------------
Example #2 Counting rows returned by a SELECT statement
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.

大意是,你可以变通一下,在SQL语句中使用 count(*) as rowcount。然后通过PDO获取其行数

考虑到效率你可以先fetchAll(),然后直接用PHP的函数count()来计算查询结果集转换为数组后的单元数
------解决方案--------------------
在大多数应用中(尤其是使用模板引擎时),fetchAll 方法简单且高效

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.