相当于mysql_num_rows或mssql_num_rows的PDO [英] PDO equivalent of mysql_num_rows or mssql_num_rows
问题描述
我知道以前曾问过这个问题,但似乎解决方案是针对所提出问题的.
I know this question has been asked before but it seems like the solutions have been specific to the problem presented.
我有一个包含数百个使用mssql_num_rows的实例的代码库.
I have a codebase with hundreds of instances where mssql_num_rows is used.
代码示例:
$db->execute($sql);
if ($db->getRowsAffected() > 0) {
$total = $db->fetch();
在db类中:
$this->rowsaffected = mssql_num_rows($this->query_result);
- 我无法创建通用的
SELECT count(*) FROM table
查询,因为我有太多特定的select语句. - 我可以运行
preg_replace
删除SELECT and FROM
之间的所有内容,然后替换为COUNT(*)
并运行第二个查询,但这假定所有查询都以某种方式设置. - 我可以先
fetchAll
然后count()
结果,但这意味着升级if语句的所有实例. - I can't create generic
SELECT count(*) FROM table
queries as I have too many specific select statements. - I could run a
preg_replace
to remove everything betweenSELECT and FROM
and then replace with aCOUNT(*)
and run a second query but this assumes all queries are setup a certain way. - I could
fetchAll
first thencount()
the results but that means upgrading all instances of the if statements.
因此,如果人们将其代码更新为PDO,那么最好替换* _num_rows函数.不是解决特定问题的方法,而是替代* _num_rows功能的方法.如果不可能的话,那么以前怎么可能呢?
So what is the best all around replacement to a *_num_rows function if people are updating their code to PDO. Not something that solves a specific problem, but something that replaces the functionality of *_num_rows. If that's not possible what allowed it to be possible before?
推荐答案
如果要计算行数,可以使用PDO做到这一点:
If you want to count the rows you can do this with PDO:
$sql = 'select * from users';
$data = $conn->query($sql);
$rows = $data->fetchAll();
$num_rows = count($rows);
在PDO中使用SELECT
语句时,无法直接对行进行计数.
There is no way to directly count rows when using a SELECT
statement with PDO.
这篇关于相当于mysql_num_rows或mssql_num_rows的PDO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!