問題描述
我正在使用 PHP PDO 擴展來創建數據庫類別表中所有項目的列表.預期結果不正確,只返回一行數據而不是全部預期的行.通過在 phpMyAdmin 控制臺中運行相同的 SQL 語句,我得到了預期的結果所有數據行的結果.我需要知道我在使用 pdo 時忽略了什么.
I am using PHP PDO extension to create a list of all items from a DB category table. The expected results are not correct, only one row of data returned instead of all rows which is expected. By running the same SQL statement within the phpMyAdmin console I get the expected results for all rows of data. I need to know what I am overlooking with pdo.
當前代碼:
$catId = 0;
$sql = "SELECT *
FROM category
WHERE cat_parent_id = :catId
ORDER BY cat_name";
$_stmt = $this->_dbConn->prepare($sql);
$_stmt->bindParam(":catId", $catId, PDO::PARAM_INT);
$_stmt->execute();
$rows = $_stmt->fetch(PDO::FETCH_ASSOC);
// display PDO result - only getting one row instead of all rows.
print_r($rows);
Array ( [cat_id] => 3
[cat_parent_id] => 0
[cat_name] => Shop
[cat_description] => Seminars
[cat_image] => c72e.gif
)
// NOTE: By running the same SQL within the phpMyAdmin
// console I get the expected results with all rows.
Array ( [cat_id] => 3
[cat_parent_id] => 0
[cat_name] => Shop
[cat_description] => Seminars
[cat_image] => c72e.gif
),
( [cat_id] => 1
[cat_parent_id] => 0
[cat_name] => Site Map
[cat_description] => List content links
[cat_image] => c83b.gif
)
推薦答案
PDOStatement::fetch()
一次只返回 1 行.
PDOStatement::fetch()
will only return 1 row at a time.
您可以使用 PDOStatement::fetchAll()
:
You could use PDOStatement::fetchAll()
:
$rows = $_stmt->fetchAll(PDO::FETCH_ASSOC);
或創建一個循環,在該循環中不斷調用 PDOStatement::fetch()
直到它返回 false
:
or create a loop where you keep calling PDOStatement::fetch()
until it returns false
:
$rows = array();
while( $row = $_stmt->fetch(PDO::FETCH_ASSOC) ) {
$rows[] = $row;
}
但后一個示例有點多余,如果您無論如何都想一次獲取所有行,除非您想解決一些內存問題.
But the latter example is a bit redundant, if you want to get all rows at once anyway, unless there are some memory concerns you want to address.
這篇關于PHP PDO SQL 只返回一行數據而不是所有行的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!