问题
I couldn't understand the exact working of the fetch/fetchall in PDO.can i get a simple example for PDO fetch for fetching each row and displays its values iteratively?
回答1:
There are a lot of examples around.. You can do a simple fetch using a while
loop too
<?php
//your PDO connection goes here.....
$stmt = $db->query('SELECT username FROM yourtable');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['username'];
}
Read the PHP Manual on PDOStatement::fetch
By using a fetchAll , you can grab all the results in a single array..
$stmt = $db->query("SELECT username FROM yourtable");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($results);
Read the PHP Manual on PDOStatement::fetchAll
回答2:
When you perform a query, you get a PDOStatement
object. That object, once the query gets executed, will be populated with the results.
Now you are given two functions:
$pdoStatement->fetch();
and
$pdoStatement->fetchAll();
fetch
will fetch one row at a time. It also advances automatically, so you don't need to call a next()
function. Just call fetch
in a loop, and you'll get all of your results. fetch
returns an array.
fetchAll
will fetch all of the rows at once. Returning an array of arrays (where each inner array is one row).
来源:https://stackoverflow.com/questions/23571676/php-pdo-fetch-row-and-print-values