Once we have data safely stored in the database, it's time to display it to visitors. When outputting using PHP PDO, we must pay attention to the proper connection and loop that will iterate through all rows in the table.
Connection and Basic Query
First, we prepare an SQL statement that will select all posts from our table. We will use the query() method because
at this step we don't need external parameters from the user.
| Command | Description |
|---|---|
fetch() |
Retrieve one row from the results. |
fetchAll() |
Retrieve all rows at once into an array. |
Code Example for List Output
Below is a practical example of how we output titles and short descriptions for all posts directly from the database:
// 1. Execute query
$stmt = $pdo->query("SELECT title, content FROM posts");
// 2. Output using a loop
while ($row = $stmt->fetch()) {
echo "<h2>" . htmlspecialchars($row['title']) . "</h2>";
echo "<div class='content'>" . $row['content'] . "</div>";
}
- Establish connection with PDO object.
- Execute SELECT query.
- Iterate through results with a
whileloop. - Output HTML elements directly from the database.
Since you already use HTML tags in the database (such as <p> and <h3>), PHP simply "outputs" them to the page, and the browser formats them correctly.