In this part of Project 2 (CRUD Blog System), we will learn how to edit and update existing blog posts using PHP and MySQL.
This is the Update part of CRUD.
What You Will Learn in This Part
- Fetch a single record by ID
- Pre-fill form with existing data
- Update database records using PHP
- Understand update workflow in real projects
Prerequisites
Make sure:
- Posts are already inserted
- You can view posts (Part 3 completed)
db.phpfile exists
Step 1: Add Edit Link in Post List
Update index.php (from Part 3)
Add this link inside the loop:
<a href="edit-post.php?id=<?php echo $row['id']; ?>">Edit</a>
Now each post has an edit option.
Step 2: Create Edit Post File
Create a new file edit-post.php
Step 3: Fetch Post Data by ID
Add this PHP code at the top of edit-post.php
<?php
include "db.php";
$id = $_GET['id'];
$query = "SELECT * FROM posts WHERE id = $id";
$result = mysqli_query($conn, $query);
$post = mysqli_fetch_assoc($result);
?>
Step 4: Create Edit Form (Pre-Filled)
<!DOCTYPE html>
<html>
<head>
<title>Edit Post</title>
</head>
<body>
<h2>Edit Blog Post</h2>
<form method="post">
<label>Post Title:</label><br>
<input type="text" name="title" value="<?php echo $post['title']; ?>" required><br><br>
<label>Post Content:</label><br>
<textarea name="content" rows="6" required><?php echo $post['content']; ?></textarea><br><br>
<input type="submit" name="update" value="Update Post">
</form>
</body>
</html>
Step 5: Update Data in Database
Add this PHP code above the HTML in edit-post.php
<?php
if (isset($_POST['update'])) {
$title = $_POST['title'];
$content = $_POST['content'];
$updateQuery = "UPDATE posts
SET title='$title', content='$content'
WHERE id=$id";
if (mysqli_query($conn, $updateQuery)) {
header("Location: index.php");
} else {
echo "Error: " . mysqli_error($conn);
}
}
?>
Step 6: Test Edit Functionality
- Open
index.php - Click Edit
- Modify title or content
- Click Update Post
- You’ll be redirected to post list
✅ Changes should be saved successfully.
Understanding the Flow
Post List → Edit Link → Edit Form → Update Query → Redirect
This is exactly how admin panels work.
Common Beginner Mistakes
- Forgetting
idin URL - Not fetching existing data
- Missing
WHERE id = ... - Page not redirecting after update
Mini Task for Students
Try to:
- Add success message
- Add cancel button
- Show post updated time
What’s Next?
➡ Project 2 – Part 5: Delete Post (Delete Data)
We will:
- Add delete functionality
- Use confirmation
- Remove records securely
