PHP CRUD Operations with MySQL (Full Code)
In this lesson: Build a complete PHP MySQL CRUD app with PDO — insert, display, edit and delete records — full source code with steps.
What is CRUD
CRUD stands for Create, Read, Update, Delete — the four things you do with stored data. A blog creates posts, reads them to show, updates them when edited, and deletes them when removed. Master these four and you can build almost any data-driven feature.
The table and connection
We use a simple students table and a PDO connection.
<?php
$pdo = new PDO("mysql:host=localhost;dbname=school", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// table: students(id, name, marks)
?>
All four operations below use this $pdo connection and prepared statements to stay safe from SQL injection.
Create (INSERT)
<?php
$sql = "INSERT INTO students (name, marks) VALUES (?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute(["Aman", 88]);
echo "Created row";
?>
The ? placeholders receive the real values from execute(), keeping user data out of the SQL text.
Read (SELECT)
<?php
$stmt = $pdo->query("SELECT id, name, marks FROM students");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $r) {
echo $r["name"] . " - " . $r["marks"] . "\n";
}
?>
fetchAll(PDO::FETCH_ASSOC) gives every row as an array keyed by column name, so you read $r["name"] directly.
Update (UPDATE)
<?php
$sql = "UPDATE students SET marks = ? WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([95, 1]);
echo "Updated row 1";
?>
The WHERE id = ? is essential — it limits the change to one student. Without it, every student's marks would change.
Delete (DELETE)
<?php
$sql = "DELETE FROM students WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([1]);
echo "Deleted row 1";
?>
Again the WHERE clause protects you — deleting without it would empty the whole table. Always target the exact record.
Common mistakes
- No WHERE on UPDATE/DELETE. This changes or deletes every row — always target one record.
- Pasting input into SQL. Use placeholders and
execute()to prevent injection. - Ignoring errors. Set
ERRMODE_EXCEPTIONand wrap risky code in try-catch. - Forgetting FETCH_ASSOC. Set it so rows are readable by column name.
Summary
- CRUD = Create, Read, Update, Delete — the four core data operations.
- They map to INSERT, SELECT, UPDATE and DELETE.
- Use PDO prepared statements for every operation to block SQL injection.
- Always add
WHEREto UPDATE and DELETE. - Read results with
fetchAll(PDO::FETCH_ASSOC).
Next, connect and secure data with PHP MySQL connection, or build a real app with login and registration.
Frequently Asked Questions
What does CRUD stand for?
Which SQL command matches each CRUD operation?
Why use prepared statements for CRUD?
Why must UPDATE and DELETE have a WHERE clause?
How do I read the results of a SELECT in PHP?
fetch() for one row or fetchAll(PDO::FETCH_ASSOC) for all rows. Then loop through them and read each column by its name.