Project 2 – Part 3: View Posts (Read Data)

In this part of Project 2 (CRUD Blog System), we will learn how to fetch and display blog posts from the database using PHP and MySQL.

This is the Read part of CRUD.


What You Will Learn in This Part

  • Fetch records from MySQL database
  • Use mysqli_query() and mysqli_fetch_assoc()
  • Display data using PHP loops
  • Show latest posts first
  • Build a basic blog listing page

Prerequisites

Before starting, make sure:

  • Database and posts table are created
  • Data is already inserted (from Part 2)
  • db.php file exists

Step 1: Database Connection File

We will reuse the same db.php file:

<?php
$host = "localhost";
$user = "root";
$password = "";
$dbname = "blog_project";

$conn = mysqli_connect($host, $user, $password, $dbname);

if (!$conn) {
    die("Database connection failed: " . mysqli_connect_error());
}
?>

Step 2: Fetch Posts from Database

Create a file index.php

<?php
include "db.php";

$query = "SELECT * FROM posts ORDER BY id DESC";
$result = mysqli_query($conn, $query);
?>

Step 3: Display Posts Using PHP Loop

Add HTML and PHP together in index.php

<!DOCTYPE html>
<html>
<head>
    <title>All Blog Posts</title>
</head>
<body>

<h2>All Blog Posts</h2>

<?php
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        ?>
        <div style="border:1px solid #ccc; padding:10px; margin-bottom:10px;">
            <h3><?php echo $row['title']; ?></h3>
            <p><?php echo nl2br($row['content']); ?></p>
            <small>Posted on: <?php echo $row['created_at']; ?></small>
        </div>
        <?php
    }
} else {
    echo "No posts found.";
}
?>

</body>
</html>

Step 4: Test the Read Functionality

  1. Open browser
  2. Visit: http://localhost/index.php
  3. You should see all inserted posts displayed
  4. Latest post appears on top

🎉 Congratulations! Your blog listing page is working.


Understanding the Code (Simple Explanation)

  • mysqli_query() → runs SQL query
  • mysqli_fetch_assoc() → fetches one row as array
  • while loop → loops through all records
  • ORDER BY id DESC → shows latest posts first

Common Beginner Mistakes

  • Forgetting include db.php
  • Wrong table name
  • Using fetch_row() instead of fetch_assoc()
  • Not checking if rows exist

Mini Task for Students

Try to:

  • Add post number
  • Limit content to 100 characters
  • Add a Read More link

Related Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *