PHP + MySQL + CSS CRUD (Procedural)

Lesson 2: Display Students (READ)

๐Ÿ“˜ Introduction

In this lesson, students will learn how to retrieve and display records from the database using MySQLi procedural programming. This is the โ€œRโ€ in CRUD โ€” READ. We will fetch all student records and display them inside a Bulma-styled table.


๐Ÿ“„ Step 1: Write SQL Query to Fetch Students

We use SELECT to retrieve all rows from the students table.


$sql = "SELECT * FROM students ORDER BY id DESC";
$result = mysqli_query($conn, $sql);

The mysqli_query() function sends the SQL command to MySQL and returns a result set.


๐Ÿ” Step 2: Loop Through Results

We use mysqli_fetch_assoc() to convert each row into an associative array.


while($row = mysqli_fetch_assoc($result)){
    echo $row['name'];
}

This loop runs once for each student record.


๐Ÿ“Š Step 3: Display Students in a Bulma Table

Bulma provides a clean table layout using the table class. We will embed PHP inside HTML to dynamically generate rows.


<table class="table is-striped is-fullwidth">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <?php
        while($row = mysqli_fetch_assoc($result)){
            echo "<tr>
                    <td>{$row['id']}</td>
                    <td>{$row['name']}</td>
                    <td>{$row['email']}</td>
                    <td>{$row['phone']}</td>
                    <td>
                        <a class='button is-small is-info' href='edit.php?id={$row['id']}'>Edit</a>
                        <a class='button is-small is-danger' href='delete.php?id={$row['id']}'>Delete</a>
                    </td>
                  </tr>";
        }
        ?>
    </tbody>
</table>

๐Ÿง  Syntax Breakdown

  • SELECT * FROM students โ€” retrieves all student records.
  • ORDER BY id DESC โ€” newest records appear first.
  • mysqli_query() โ€” sends SQL to MySQL.
  • mysqli_fetch_assoc() โ€” fetches each row as an associative array.
  • echo "<tr>...</tr>" โ€” prints dynamic HTML.

๐Ÿงช Exercise

Modify the SQL query to sort students alphabetically by name:


SELECT * FROM students ORDER BY name ASC

Reload the page and confirm the list is now alphabetical.

Edit the panels below and press Run to preview. Nothing you type here is saved โ€” refreshing the page restores the original starter code.

← Previous Next lesson →