As already posted by the other users, PDOStatement::setFetchMode
only sets the default fetch mode for a prepared statement. It must be one of the PDO::FETCH_*
constants, as described in the documentation for PDOStatement::fetch.
In order to fetch records from a db table you can call fetch()
as part of a while
statement, or directly call fetchAll()
.
- Technically, the
fetch()
method is used to fetch only one record. But, by applying the while
statement, you are telling the PHP engine to fetch a new record in each iteration step.
- Comparing with
fetch()
, the fetchAll()
method is designed to fetch multiple records at once. A test says, that "it's faster, but requires more memory". It's up to you to decide, if the test convinces you.
Anyway, since you are trying to fetch multiple records, I recommend using the fetchAll
method. My personal reason for the choice is, that this way the use of a while
statement is avoided. I always try to completely avoid while
statements in my codes, because they can produce infinite loops. That doesn't mean though, that they shouldn't be used by you. But use them with care.
Now, the first parameter of the fetchAll()
method is fetch_style
. It corresponds exactly to the parameter of the setFetchMode()
and to the first parameter of the fetch()
method. So, again, read the parameters list of PDOStatement::fetch in detail, so you know which values it can take.
Also, I would recommend you to try to separate fetching codes from the presentation ones. Fetch all data that you need in arrays and later iterate through them as usual, in order to formatted-display the results. And try to avoid building HTML elements from PHP code, if possible.
At last, here is a very good PDO tutorial: (The only proper) PDO tutorial.
Good luck!
<?php
try {
// Connect to db.
$conn = new PDO(
'mysql:host=localhost;port=3306;dbname=books;charset=utf8'
, 'yourusername'
, 'yourpassword'
, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_PERSISTENT => true,
)
);
// Prepare and execute query.
$sql = 'SELECT * FROM bestsellers';
$stmt = $conn->prepare($sql);
$stmt->execute();
// Get the result set as an associative array.
$bestsellers = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
} catch (Exception $exc) {
echo $exc->getMessage();
exit();
}
?>
<table>
<?php
foreach ($bestsellers as $bestseller) {
$title = $bestseller['title'];
$genre = $bestseller['genre'];
$rating = $bestseller['rating'];
$price = $bestseller['price'];
?>
<tr class="bestseller-game-template">
<td class="col-sm-3">
<?php echo $title; ?>
</td>
<td class="col-sm-3">
<?php echo $genre; ?>
</td>
<td class="col-sm-3">
<?php echo $rating; ?>
</td>
<td class="col-sm-3">
<?php echo $price; ?>
</td>
</tr>
<?php
}
?>
</table>