周围有许多相互矛盾的说法。在 PHP 中使用 PDO 获取行数的最佳方法是什么?在使用 PDO 之前,我只是简单地使用了 mysql_num_rows
。
fetchAll
是我不想要的东西,因为我有时可能会处理大型数据集,所以不适合我使用。
你有什么建议吗?
最佳答案
当您只需要行数而不需要数据本身时,无论如何都不应该使用这样的函数。相反,请使用如下代码要求数据库进行计数:
$sql = "SELECT count(*) FROM `table` WHERE foo = ?";
$result = $con->prepare($sql);
$result->execute([$bar]);
$number_of_rows = $result->fetchColumn();
为了获取行数以及检索到的数据,PDO 具有 PDOStatement::rowCount()
,这显然确实在 MySql 中使用 buffered queries 工作(默认启用)。
但不能保证其他驱动程序。来自 PDO 文档:
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.
但在这种情况下,您可以使用数据本身。假设您选择了合理数量的数据,可以使用 PDO::fetchAll() 将其提取到数组中,然后 count() 将为您提供行数。
编辑:上面的代码示例使用了准备好的语句,但如果查询不使用任何变量,则可以使用 query() 函数代替:
$nRows = $pdo->query('select count(*) from blah')->fetchColumn();
echo $nRows;
关于php - PDO 的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40486984/