php - 使用 PDO 进行行计数

标签 php mysql pdo

周围有许多相互矛盾的说法。在 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/57946911/

相关文章:

PHP/JSON : $_POST array is received incomplete

mysql - 我无法让 LEFT JOIN 工作

php - PDO fetch() 没有错误但没有结果

php - 其他类(class)的PDO有什么问题?

php - 如何在 my.cnf 文件中设置内存限制

php - Joomla 2.5 中的 JS 工作扩展

php - Laravel 4 从构造中创建表

sql - 限制多对多连接查询的结果

mysql - 在不丢失数据的情况下重命名 Doctrine 2 中的字段

php - PDO for 循环问题