Performing CRUD Operations in PHP Using PDO
What is CRUD?
CRUD stands for:
Operation | Purpose |
---|---|
Create | Add new records to the database |
Read | Retrieve data from the database |
Update | Modify existing data |
Delete | Remove records from the database |
These four operations are the core actions in most dynamic PHP web apps — from blogs and admin panels to inventory systems and CMS platforms.
Prerequisites
Make sure:
- You’ve set up a database named
testdb
- There’s a table
users
with fields:id
,name
,email
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
And establish a PDO connection:
<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
1. CREATE – Insert New Record
HTML Form (create.html
)
<form action="create.php" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="email" name="email"><br>
<input type="submit" value="Add User">
</form>
HP Logic (create.php
)
<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->execute(['name' => $name, 'email' => $email]);
echo "User added successfully.";
}
?>
2. READ – Fetch and Display Records
Example (read.php
)
<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->query("SELECT * FROM users");
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th><th>Actions</th></tr>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['email']}</td>
<td>
<a href='edit.php?id={$row['id']}'>Edit</a> |
<a href='delete.php?id={$row['id']}'>Delete</a>
</td>
</tr>";
}
echo "</table>";
?>
3. UPDATE – Modify an Existing Record
Edit Form (edit.php
)
<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root", "");
$id = $_GET['id'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(['id' => $id]);
$user = $stmt->fetch();
?>
<form action="update.php" method="post">
<input type="hidden" name="id" value="<?= $user['id'] ?>">
Name: <input type="text" name="name" value="<?= $user['name'] ?>"><br>
Email: <input type="email" name="email" value="<?= $user['email'] ?>"><br>
<input type="submit" value="Update">
</form>
Update Logic (update.php
)
<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root", "");
$id = $_POST['id'];
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$stmt = $pdo->prepare("UPDATE users SET name = :name, email = :email WHERE id = :id");
$stmt->execute(['name' => $name, 'email' => $email, 'id' => $id]);
echo "User updated successfully.";
?>
4. DELETE – Remove a Record
Example (delete.php
)
<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root", "");
$id = $_GET['id'];
$stmt = $pdo->prepare("DELETE FROM users WHERE id = :id");
$stmt->execute(['id' => $id]);
echo "User deleted.";
?>
You can add a confirmation popup in HTML or JavaScript before triggering deletion.
Common Mistakes in CRUD
- Not using prepared statements (leads to SQL injection)
- Forgetting to escape user input (e.g.,
htmlspecialchars()
) - Not checking if record exists before editing/deleting
- Hardcoding connection in every file (consider using a
config.php
) - Failing to use proper HTTP methods (
GET
vsPOST
)
Best Practices
- Always use prepared statements for all queries
- Validate and sanitize all user inputs
- Separate database configuration (
config.php
) - Redirect after insert/update/delete (avoid resubmission)
- Show user-friendly messages on success or error
Notes:
- CRUD operations are essential for building interactive PHP apps
- PDO provides a secure way to handle Create, Read, Update, and Delete
- Use
try...catch
blocks and prepared statements for safety - Combine HTML forms with PHP scripts to interact with databases
Practice Tasks
Task 1: Add Product
Create a CRUD system for a products
table with fields: id
, product_name
, price
Task 2: User Management
Extend the current CRUD app to:
- Display total users
- Sort users alphabetically
- Add pagination (if more than 10 users)
Task 3: Secure Delete
Modify delete.php
to ask for confirmation before deleting a record using a form (POST-based delete)
💡 Explore More PHP Learning Tools & Resources
PHP Practice Quiz
Test your PHP skills with real coding questions and scoring.
PHP Interview Questions
Prepare for interviews with common PHP questions and answers.
Educational AI Tutor
Ask PHP questions and get instant AI-powered explanations.
Question Generator
Auto-generate PHP interview questions for quick practice.