PHP + MySQL + CSS CRUD (Procedural)
Lesson 5: Delete Student (DELETE)
π Introduction
In this lesson, students will learn how to delete a student record from the database using MySQLi procedural programming. This is the βDβ in CRUD β DELETE. We will create a simple delete script that removes a record based on its ID.
Deleting data is a critical part of CRUD applications, and students must understand how to safely handle deletion operations.
ποΈ Step 1: Capture the Student ID
When the user clicks the Delete button, they are redirected to:
delete.php?id=3
We use $_GET['id'] to capture the student ID.
$id = $_GET['id'];
β οΈ Step 2: Delete the Record
We use the SQL DELETE command to remove the record from the database.
$sql = "DELETE FROM students WHERE id = $id";
mysqli_query($conn, $sql);
This removes the student permanently.
π Step 3: Redirect Back to Main Page
After deleting the record, redirect the user back to the student list.
header("Location: index.php");
exit;
π§ Syntax Breakdown
$_GETβ retrieves the student ID from the URL.DELETE FROM students WHERE id = Xβ deletes the specific record.mysqli_query()β executes the SQL delete command.header()β redirects after deletion.
π§ͺ Exercise
Create a confirmation page before deleting a record:
- Ask the user: βAre you sure you want to delete this student?β
- Provide two buttons: Yes and No
- If βNoβ is clicked, redirect back to
index.php
This teaches students how to prevent accidental deletions.
Edit the panels below and press Run to preview. Nothing you type here is saved β refreshing the page restores the original starter code.