PHP5 的 PDO rowCount MySQL 问题的解决方法
我最近开始使用 PHP5 开发一个新项目,并希望使用他们的 PDO 类。 问题是 MySQL PDO 驱动程序不支持 rowCount(),因此无法运行查询,然后获取受影响的行数或返回的行数,就我而言,这是一个相当大的问题。 我想知道之前是否有其他人处理过这个问题,以及您做了什么来解决这个问题。 必须执行 fetch() 或 fetchAll() 来检查是否有任何行受到影响或返回,对我来说似乎是一种黑客行为,我宁愿只执行 $stmt->numRows() 或类似的操作。
I've recently started work on a new project using PHP5 and want to use their PDO classes for it. The problem is that the MySQL PDO Driver doesn't support rowCount() so there's no way to run a query and then get the number of affected rows, or rows returned, which is a pretty big issue as far as I'm concerned. I was wondering if anyone else has dealt with this before and what you've done to work around it. Having to do a fetch() or fetchAll() to check if any rows were affected or returned seems like a hack to me, I'd rather just do $stmt->numRows() or something similar.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在原始
SELECT
查询之后发出SELECT FOUND_ROWS()
查询来获取行数。另请参阅:有关 FOUND_ROWS() 的 MySQL 文档
You can issue a
SELECT FOUND_ROWS()
query right after the originalSELECT
query to get row count.See also: MySQL Docs on FOUND_ROWS()
对于那些使用 MySQL 存储过程的人来说,这个解决方案实际上并不可行。 我建议您做的是让存储过程创建两个行集。 第一个将包含一行和一列,包含记录数。 第二个是您将用于获取该行数的记录集。
无限行数可以是
SELECT COUNT(*)
,其WHERE
子句与第二个行集完全相同,但不带LIMIT
/OFFSET
子句。另一个想法可能是创建一个临时表。 使用
SELECT
语句填充临时表。 然后,您可以对第一个行集使用 SELECT COUNT(*) FROM tmpTable,对第二个行集使用 SELECT * FROM tmpTable。For those of you who are using MySQL stored procedures, this solution isn't really feasible. What I would suggest that you do is have your stored procedure create two rowsets. The first one will contain one row and one column, containing the number of records. The second will be the recordset you will use for fetching that number of rows.
The number of unlimited rows can be a
SELECT COUNT(*)
with the exact sameWHERE
clause as the second rowset without theLIMIT
/OFFSET
clauses.Another idea could be to create a temporary table. Use your
SELECT
statement to populate the temporary table. Then you can useSELECT COUNT(*) FROM tmpTable
for your first rowset andSELECT * FROM tmpTable
for your second.这个问题基于几个错误的假设和一个过时的陈述。
首先,不要混淆受影响行数和选定行数。 PDO 早在 09 年就支持前者。
说到 SELECT 语句返回的行数 - 您只是不需要该数字。 你拥有的数据就足够了。
是的,现在 rowCount() 也支持从 mysql 选择的行数。 但同样,在普通的网络应用程序中你并不需要这个数字。
This question is based on several false assumptions and one outdated statement.
First of all, do not confuse number of affected and selected rows. PDO supported the former even back in '09.
Speaking of number of rows returned by SELECT statement - you just don't need that number. The data you have is enough.
And yeah, nowadays
rowCount()
supports number of rows selected from mysql as well. But again - you don't need that number in an average web-application anyway.