3 回答

TA貢獻1828條經(jīng)驗 獲得超13個贊
看一下PDOStatement.fetchAll方法。您也可以fetch在迭代器模式中使用。
fetchAll來自PHP文檔的的代碼示例:
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);
結(jié)果:
Array
(
[0] => Array
(
[NAME] => pear
[COLOUR] => green
)
[1] => Array
(
[NAME] => watermelon
[COLOUR] => pink
)
)

TA貢獻1851條經(jīng)驗 獲得超4個贊
有三種方法來獲取PDO語句返回的多行。
最簡單的方法就是迭代PDOStatement本身:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// iterating over a statement
foreach($stmt as $row) {
echo $row['name'];
}
另一個是在熟悉的while語句中使用fetch()方法獲取行:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
echo $row['name'];
}
但是對于現(xiàn)代Web應(yīng)用程序,我們應(yīng)該將datbase迭代與輸出分開,因此,最方便的方法是使用fetchAll()方法一次獲取所有行:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// fetching rows into array
$data = $stmt->fetchAll();
然后將它們輸出到模板中:
<ul>
<?php foreach($data as $row): ?>
<li><?=$row['name']?></li>
<?php endforeach ?>
</ul>
請注意,PDO支持許多復(fù)雜的提取模式,從而允許fetchAll()返回許多不同格式的數(shù)據(jù)。

TA貢獻1827條經(jīng)驗 獲得超9個贊
$st = $data->prepare("SELECT * FROM exampleWHERE example LIKE :search LIMIT 10");
添加回答
舉報