Once we have our data safely stored in the database, it's time to display it to our visitors. When displaying data using PHP PDO, we need to focus on a proper connection and a loop that iterates through all rows in the table.
1. Connection and Basic Query
First, we prepare the SQL statement to select all posts from our table. We will use the query() method since we don't need any external user parameters in this step.
| Command | Description |
|---|---|
fetch() |
Fetches a single row from the results. |
fetchAll() |
Fetches all rows at once into an array. |
2. Code Example for Listing Posts
Below is a practical example of how to display titles and content for all posts directly from the database:
// 1. Execute the query
$stmt = $pdo->query("SELECT naslov, vsebina FROM objave");
// 2. Display using a loop
while ($row = $stmt->fetch()) {
echo "<h2>" . htmlspecialchars($row['naslov']) . "</h2>";
echo "<div class='content'>" . $row['vsebina'] . "</div>";
}
- Establish a connection with the PDO object.
- Execute the SELECT query.
- Use a
whileloop to iterate through the results. - Output HTML elements directly from the database.
Since you are already using HTML tags (like <p> and <h3>) in the database, PHP simply outputs them to the page, and the browser renders them correctly.