本文介紹了PDO 中的 'fetch' 只得到一個(gè)結(jié)果的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我有這個(gè)代碼:
$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
)
它有一個(gè)結(jié)果,但我在表中有兩行;這是為什么?
It has one result, but I have two rows in the table; why is that?
推薦答案
應(yīng)該使用 Fetch 來(lái)顯示數(shù)據(jù)庫(kù)結(jié)果中的下一行.
Fetch should be used to display the next row from the database result.
要獲取所有行,您應(yīng)該使用 fetchAll();
To get all rows, you should use fetchAll();
- PDOStatement::fetch — 從結(jié)果集
- PDOStatement::fetchAll() — 返回包含結(jié)果集的所有行
- 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 來(lái)
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);
}
?>
這篇關(guān)于PDO 中的 'fetch' 只得到一個(gè)結(jié)果的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!