How to use PDO to fetch results array in PHP?
Take a look at the PDOStatement.fetchAll
method. You could also use fetch
in an iterator pattern.
Code sample for fetchAll
, from the PHP documentation:
<?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);
Results:
Array
(
[0] => Array
(
[NAME] => pear
[COLOUR] => green
)
[1] => Array
(
[NAME] => watermelon
[COLOUR] => pink
)
)
There are three ways to fetch multiple rows returned by PDO statement.
The simplest one is just to iterate over PDOStatement itself:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// iterating over a statement
foreach($stmt as $row) {
echo $row['name'];
}
another one is to fetch rows using fetch() method inside a familiar while statement:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
echo $row['name'];
}
but for the modern web application we should have our datbase iteractions separated from output and thus the most convenient method would be to fetch all rows at once using fetchAll() method:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// fetching rows into array
$data = $stmt->fetchAll();
or, if you need to preprocess some data first, use the while loop and collect the data into array manually
$result = [];
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
$result[] = [
'newname' => $row['oldname'],
// etc
];
}
and then output them in a template:
<ul>
<?php foreach($data as $row): ?>
<li><?=$row['name']?></li>
<?php endforeach ?>
</ul>
Note that PDO supports many sophisticated fetch modes, allowing fetchAll() to return data in many different formats.