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/40486984/

相关文章:

php - PDO - array_map 返回键中的对象 ID

php - 默认情况下,PDO 是否始终使用模拟的准备好的语句?

php - MySQL/PHP 批量删除使用数组 : Best method?

java - 如何读取属性文件并连接 MySQL 数据库?

java - 如何为具有复合主键和外键的 oneToMany 关系创建 Hibernate 映射文件?

mysql - mysql中的排序规则有什么用

php - MySQL 全文搜索,通过相关性和整数进行连接和排序,使用 PHP 和 PDO

php - drupal 在哪里保存我从其表中的内容类型上传的图像路径?

php - 无法使用 WP REST API 2.0 插件通过基本身份验证进行身份验证

javascript - 如何使用 codeigniter 调用 ajax 中的函数来更新