How to work with all the rows of a result set

Another method of the PDOStatement class

fetchAll() 
// Returns an array for all of the rows in the result set.

Code that returns a result set of two or more rows

$query = "SELECT productCode, productName, listPrice
    FROM products
    WHERE categoryID = :category_id;"
$statement = $db->prepare($query);
$statement->bindValue(":category_id", $category_id);
$statement->execute();
$products = $statement->fetchAll();
$statement->closeCursor();

How to use a foreach statement to display the result set in an HTML table

<!-- HTML code to begin a table goes here -->
<?php foreach ($products as $product) { ?>
  <td><?php echo $product['productCode']; ?></td>
  <td><?php echo $product['productName']; ?></td>
  <td><?php echo $product['listPrice']; ?></td>
</tr>
<?php } ?>
<!-- HTML code to end table goes here -->

Description

Back