問題描述
我知道以前有人問過這個問題,但似乎解決方案是針對所提出的問題的.
I know this question has been asked before but it seems like the solutions have been specific to the problem presented.
我有一個包含數(shù)百個使用 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();
在數(shù)據(jù)庫類中:
$this->rowsaffected = mssql_num_rows($this->query_result);
- 我無法創(chuàng)建通用的
SELECT count(*) FROM table
查詢,因為我有太多特定的選擇語句. - 我可以運行
preg_replace
來刪除SELECT 和 FROM
之間的所有內(nèi)容,然后用COUNT(*)
替換并運行第二個查詢但這假設(shè)所有查詢都以某種方式設(shè)置. - 我可以先
fetchAll
然后count()
結(jié)果,但這意味著升級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 函數(shù)的方法.不是解決特定問題的東西,而是替代 *_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?
推薦答案
如果你想計算行數(shù),你可以使用 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);
如 SELECT 語句與 PDO 一起使用時,無法直接計算行數(shù).rowcount.php" rel="nofollow noreferrer">文檔.
There is no way to directly count rows when using a SELECT
statement with PDO as stated in the docs.
PDOStatement::rowCount() 返回受相應(yīng)的最后一個 DELETE、INSERT 或 UPDATE 語句影響的行數(shù)PDOStatement 對象.
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
僅在絕對需要計數(shù)時才進行行計數(shù),否則您可以驗證查詢是否與其他方法一起使用.如果您希望從表中返回數(shù)千行,您也不應(yīng)該使用此方法,而是在查詢中使用 COUNT()
函數(shù)來執(zhí)行計數(shù).
Only do a row count if you absolutely need the count, otherwise you can verify that the query worked with other methods. You should also not use this method if you expect to be returning thousands of rows from a table, instead, use the COUNT()
function in a query for just performing the count.
這篇關(guān)于相當(dāng)于 mysql_num_rows 或 mssql_num_rows 的 PDO的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!