PHP5 的 PDO rowCount MySQL 问题的解决方法

2021-12-26 00:00:00 php pdo

我最近开始使用 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.

推荐答案

您可以在原始 SELECT 查询之后立即发出 SELECT FOUND_ROWS() 查询以获取行数.

You can issue a SELECT FOUND_ROWS() query right after the original SELECT query to get row count.

$pdo->query("SELECT * FROM users");
$foundRows = $pdo->query("SELECT FOUND_ROWS()")->fetchColumn();

另见:关于 FOUND_ROWS 的 MySQL 文档()

相关文章