PDO 的 rowCount() 不适用于 PHP 5.2.6+
所以我已经使用 PHP 的 PDO 作为我的数据库 goto 类有一段时间了,不幸的是今天在客户端服务器上调试一段时间后(安装了 PHP 5.2.6)我发现 这个。 我们尝试升级到最新的稳定版本(5.2.9),但问题仍然存在。
有人找到解决方法吗?
So I've been using PHP's PDO as my database goto class for a while now, unfortunately today after debugging for a while on a client's server (with PHP 5.2.6 installed) I discover this. We tried upgrading to the newest stable release (5.2.9) but the problem persists.
Has anyone found a workaround?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
数据库可以为您提供行数计数的唯一方法是运行查询并计算行数。
mysql 扩展默认使用缓冲查询模式,这会导致在控制权返回给 PHP 之前将整个数据集提取到内存中,并且可以开始处理行。
PDO 默认使用无缓冲模式,这会降低页面加载时间的延迟,并且通常是您想要的。 代价是 rowCount() 在获取整个数据集之前不会返回有效信息。
那么你如何得到这个计数呢?
简单的:
但这正是旧的 mysql 扩展实际上在幕后所做的事情; 这是获得该计数的唯一方法。
The only way that databases can give you a count for the number of rows is by running the query and counting the number of rows.
The mysql extension uses a buffered query mode by default that causes the entire dataset to be fetched into memory before control is returned to PHP and it can start to process the rows.
PDO uses an unbuffered mode by default which leads to lower latency in the page load time and is generally what you want. The trade off is that rowCount() won't return valid information until the entire dataset has been fetched.
So how do you get that count?
Easy:
But that's exactly what the old mysql extension is actually doing under the covers; it's the only way to get that count.
您可以通过 MySQL 本身使用 < code>FOUND_ROWS() function,不确定是否有更好的替代方案。
编辑:似乎 MySQL 能够做到这一点的唯一原因是它在内部获取所有结果行并缓冲它们,以便能够为您提供此信息。 请参阅
mysql_unbuffered_query()
。 如果您使用该函数而不是mysql_query()
,则mysql_num_rows()
函数将不起作用。 如果您在使用 PDO 时确实需要知道行数,可以将 PDO 中的所有行提取到数组中,然后使用count()
。You could do it through MySQL itself by using the
FOUND_ROWS()
function, not sure if there are any better alternatives.Edit: It seems as though the only reason this was possible with MySQL is because it internally fetched all the result rows and buffered them, to be able to give you this information. See
mysql_unbuffered_query()
. If you use that function instead ofmysql_query()
, themysql_num_rows()
function will not work. If you really need to know the number of rows while using PDO, you can fetch all of the rows from PDO into an array and then usecount()
.请注意,不应将 rowCount() 用于 SELECT 查询,因为 PDOStatement->rowCount() 返回受相应 PDOStatement 对象执行的最后一个 DELETE、INSERT 或 UPDATE 语句影响的行数。
相反,您可以使用 fetchAll() 进入数组,然后使用 count()。
Notice you should not use rowCount() for SELECT queries since PDOStatement->rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
Instead you might use fetchAll() into an array and then count().