本文介紹了PDO 中的 'fetch' 只得到一個結果的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有這個代碼:
$sql = new PDO('mysql:host=localhost;dbname=b', 'root', 'root');
$f = $sql->query('select * from user');
$sql->setFetchMode(PDO::FETCH_ASSOC);
while($row = $f->fetch()){
print_r($row);
}
輸出是
Array
(
[id] => 1
[name] => turki
[mail] => ablaf
[pass] => 144
)
Array
(
[id] => 2
[name] => wrfwer
[mail] => fwerf
[pass] => werf
)
這就是我真正想要的.但是如果我這樣做
And that's what I really want. But if I do this
<?php
$sql = new PDO('mysql:host=localhost;dbname=b', 'root', 'root');
$f = $sql->query('select * from user');
$f->setFetchMode(PDO::FETCH_ASSOC);
print_r($f->fetch());
?>
輸出是
Array
(
[id] => 1
[name] => turki
[mail] => ablaf
[pass] => 144
)
它有一個結果,但我在表中有兩行;這是為什么?
It has one result, but I have two rows in the table; why is that?
推薦答案
應該使用 Fetch 來顯示數據庫結果中的下一行.
Fetch should be used to display the next row from the database result.
要獲取所有行,您應該使用 fetchAll();
To get all rows, you should use fetchAll();
- PDOStatement::fetch — 從結果集
- PDOStatement::fetchAll() — 返回包含結果集的所有行
- PDOStatement::fetch — Fetches the next row from a result set
- PDOStatement::fetchAll() — Returns an array containing all of the result set rows
將您的示例更改為:
<?php
$sql = new PDO('mysql:host=localhost;dbname=b', 'root', 'root');
$f = $sql->query('select * from user');
$f->setFetchMode(PDO::FETCH_ASSOC);
print_r($f->fetchAll());
?>
或者如果你想使用 PDOStatement::fetch 來
or if you want use PDOStatement::fetch to
<?php
$sql = new PDO('mysql:host=localhost;dbname=b', 'root', 'root');
$f = $sql->query('select * from user');
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
print_r($row);
}
?>
這篇關于PDO 中的 'fetch' 只得到一個結果的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!