PHP + MySQL + CSS CRUD (Procedural)

Lession 4: Edit Student (UPDATE)

📘 Introduction

In this lesson, students will learn how to update existing student records using MySQLi procedural programming. This is the “U” in CRUD — UPDATE. We will load a student’s current data into a form, allow the user to edit it, and then save the changes back to the database.


📄 Step 1: Retrieve the Student Record

When the user clicks the Edit button, they are redirected to edit.php?id=1. We use $_GET['id'] to retrieve the student’s ID.


$id = $_GET['id'];

$sql = "SELECT * FROM students WHERE id = $id";
$result = mysqli_query($conn, $sql);
$student = mysqli_fetch_assoc($result);

The $student array now contains the student’s current information.


📝 Step 2: Pre-Fill the Edit Form

We display a form with the student’s existing data already filled in.


<input class="input" type="text" name="name" value="<?= $student['name']; ?>" required>

This allows the user to modify the values.


🗄️ Step 3: Update the Database

When the form is submitted, we capture the updated values and run an UPDATE query.


if(isset($_POST['update'])){
    $name  = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];

    $sql = "UPDATE students 
            SET name='$name', email='$email', phone='$phone'
            WHERE id=$id";

    mysqli_query($conn, $sql);

    header("Location: index.php");
    exit;
}

🧠 Syntax Breakdown

  • $_GET — retrieves the student ID from the URL.
  • SELECT ... WHERE id = X — fetches the specific student.
  • UPDATE students SET ... — updates the record.
  • mysqli_fetch_assoc() — converts the result into an array.
  • header() — redirects after saving.

🧪 Exercise

Add validation to ensure:

  • The phone number is not empty.
  • The email address is valid.

Display an error message if validation fails.

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 →