In this part of Project 2 (CRUD Blog System), we will learn how to delete blog posts from the database using PHP and MySQL.
This is the Delete part of CRUD.
What You Will Learn in This Part
- Add delete functionality
- Pass ID using URL
- Delete records securely
- Use confirmation before deleting
- Understand real-world delete flow
Prerequisites
Before starting:
- Insert, View, and Edit functionalities are working
db.phpfile exists- Posts are visible in
index.php
Step 1: Add Delete Link in Post List
Open index.php and add this link inside the loop:
<a href="delete-post.php?id=<?php echo $row['id']; ?>"
onclick="return confirm('Are you sure you want to delete this post?');">
Delete
</a>
This confirmation prevents accidental deletion.
Step 2: Create Delete File
Create a file named delete-post.php
Step 3: Delete Post Using ID
Add this code in delete-post.php
<?php
include "db.php";
$id = $_GET['id'];
$query = "DELETE FROM posts WHERE id = $id";
if (mysqli_query($conn, $query)) {
header("Location: index.php");
} else {
echo "Error: " . mysqli_error($conn);
}
?>
Step 4: Test Delete Functionality
- Open
index.php - Click Delete
- Confirm deletion
- Post should be removed from database
- Page redirects back to post list
🎉 Delete functionality is working.
Understanding Delete Flow
Click Delete → Confirm → PHP → MySQL → Redirect
This is how admin delete actions work in real projects.
Important Security Notes
For now, this is basic deletion.
Later we will improve:
- Prepared statements
- Token-based deletion
- Admin-only access
Common Beginner Mistakes
- Forgetting
WHEREclause - Wrong column name
- Not redirecting after delete
- No confirmation popup
Mini Task for Students
Try to:
- Add success message
- Restrict delete without login
- Use POST instead of GET (advanced)
Project 2 Completed 🎉
You have now built:
- Insert Post
- View Posts
- Edit Post
- Delete Post
This is a complete CRUD system.
