TExcelTAD
Home › PHP › PHP CRUD

PHP CRUD

CRUD stands for the four things almost every application does with stored data: Create, Read, Update and Delete. A to-do list, a shop's product catalogue and a blog's post editor are all CRUD screens with different fields.

In this lesson we build a small, reusable CRUD layer for a tasks table using PDO, SQLite and prepared statements.

Operation SQL PDO method that tells you the result
Create INSERT INTO ... VALUES (...) lastInsertId()
Read SELECT ... WHERE ... fetch() / fetchAll()
Update UPDATE ... SET ... WHERE ... rowCount()
Delete DELETE FROM ... WHERE ... rowCount()

Create and Read

We start by creating the table and two helper functions. Every value goes through a placeholder, and the functions return plain PHP values so the rest of the program doesn't need to know about SQL.

php · try it yourself
<?php
$pdo = new PDO('sqlite::memory:', options: [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE tasks (
    id       INTEGER PRIMARY KEY AUTOINCREMENT,
    title    TEXT NOT NULL,
    priority INTEGER NOT NULL DEFAULT 2,
    done     INTEGER NOT NULL DEFAULT 0
)');

function createTask(PDO $pdo, string $title, int $priority = 2): int {
    $stmt = $pdo->prepare('INSERT INTO tasks (title, priority) VALUES (?, ?)');
    $stmt->execute([$title, $priority]);
    return (int) $pdo->lastInsertId();
}

function findTask(PDO $pdo, int $id): ?array {
    $stmt = $pdo->prepare('SELECT * FROM tasks WHERE id = ?');
    $stmt->execute([$id]);
    return $stmt->fetch() ?: null;   // fetch() returns false when nothing matches
}

$id = createTask($pdo, 'Write report', 1);
createTask($pdo, 'Book dentist');
echo "Created task #$id\n";

print_r(findTask($pdo, $id));
var_dump(findTask($pdo, 99));
Created task #1
Array
(
    [id] => 1
    [title] => Write report
    [priority] => 1
    [done] => 0
)
NULL

Tip: fetch() returns false when there is no row. Converting that to null (with ?: null) and declaring the return type ?array makes "not found" explicit for callers.

Reading lists with filters

A list page usually needs optional filters and a sort order. Values go into placeholders; the sort column comes from an allow-list, because identifiers can't be bound.

php · try it yourself
<?php
$pdo = new PDO('sqlite::memory:', options: [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT, priority INTEGER, done INTEGER DEFAULT 0)');
$ins = $pdo->prepare('INSERT INTO tasks (title, priority, done) VALUES (?, ?, ?)');
foreach ([['Write report', 1, 0], ['Book dentist', 2, 1], ['Clean garage', 3, 0], ['Pay rent', 1, 1]] as $row) {
    $ins->execute($row);
}

function listTasks(PDO $pdo, ?bool $done = null, string $sort = 'id'): array {
    $sort = in_array($sort, ['id', 'title', 'priority'], true) ? $sort : 'id';
    $sql = 'SELECT id, title, priority, done FROM tasks';
    $params = [];
    if ($done !== null) {
        $sql .= ' WHERE done = ?';
        $params[] = (int) $done;
    }
    $stmt = $pdo->prepare("$sql ORDER BY $sort, id");
    $stmt->execute($params);
    return $stmt->fetchAll();
}

function show(array $tasks): void {
    foreach ($tasks as $t) {
        printf("  [%s] #%d %-13s p%d\n", $t['done'] ? 'x' : ' ', $t['id'], $t['title'], $t['priority']);
    }
}

echo "Open tasks by priority:\n";
show(listTasks($pdo, done: false, sort: 'priority'));
echo "Everything by title:\n";
show(listTasks($pdo, sort: 'title'));
echo "Bad sort column falls back to id:\n";
show(listTasks($pdo, done: true, sort: 'title; DROP TABLE tasks'));
Open tasks by priority:
  [ ] #1 Write report  p1
  [ ] #3 Clean garage  p3
Everything by title:
  [x] #2 Book dentist  p2
  [ ] #3 Clean garage  p3
  [x] #4 Pay rent      p1
  [ ] #1 Write report  p1
Bad sort column falls back to id:
  [x] #2 Book dentist  p2
  [x] #4 Pay rent      p1

Update and Delete

UPDATE and DELETE must always have a WHERE clause — without one they affect every row. rowCount() tells you how many rows were changed, which is the easiest way to detect "id not found".

php · try it yourself
<?php
$pdo = new PDO('sqlite::memory:', options: [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT, priority INTEGER, done INTEGER DEFAULT 0)');
$pdo->exec("INSERT INTO tasks (title, priority) VALUES ('Write report', 1), ('Book dentist', 2), ('Clean garage', 3)");

function updateTask(PDO $pdo, int $id, array $changes): bool {
    $allowed = array_intersect_key($changes, array_flip(['title', 'priority', 'done']));
    if (!$allowed) {
        return false;
    }
    $set = implode(', ', array_map(fn($col) => "$col = :$col", array_keys($allowed)));
    $stmt = $pdo->prepare("UPDATE tasks SET $set WHERE id = :id");
    $stmt->execute($allowed + ['id' => $id]);
    return $stmt->rowCount() === 1;
}

function deleteTask(PDO $pdo, int $id): bool {
    $stmt = $pdo->prepare('DELETE FROM tasks WHERE id = ?');
    $stmt->execute([$id]);
    return $stmt->rowCount() > 0;
}

var_dump(updateTask($pdo, 2, ['done' => 1, 'priority' => 1]));
var_dump(updateTask($pdo, 42, ['done' => 1]));
var_dump(updateTask($pdo, 1, ['owner' => 'me']));   // unknown column ignored
var_dump(deleteTask($pdo, 3));
var_dump(deleteTask($pdo, 3));                       // already gone

foreach ($pdo->query('SELECT * FROM tasks') as $t) {
    echo implode(' | ', $t), "\n";
}
bool(true)
bool(false)
bool(false)
bool(true)
bool(false)
1 | Write report | 1 | 0
2 | Book dentist | 1 | 1

Note: updateTask() builds the SET list dynamically, but only from column names in a fixed allow-list. The values still travel through named placeholders.

Putting it in a class

In real projects the helpers live in a repository class that receives the PDO connection in its constructor. The rest of the application calls methods like $repo->complete(1) and never sees SQL.

php · try it yourself
<?php
final class TaskRepository
{
    public function __construct(private PDO $pdo)
    {
        $pdo->exec('CREATE TABLE IF NOT EXISTS tasks (
            id INTEGER PRIMARY KEY, title TEXT NOT NULL, done INTEGER NOT NULL DEFAULT 0)');
    }

    public function add(string $title): int
    {
        $this->pdo->prepare('INSERT INTO tasks (title) VALUES (?)')->execute([$title]);
        return (int) $this->pdo->lastInsertId();
    }

    public function complete(int $id): bool
    {
        $stmt = $this->pdo->prepare('UPDATE tasks SET done = 1 WHERE id = ?');
        $stmt->execute([$id]);
        return $stmt->rowCount() === 1;
    }

    public function remove(int $id): bool
    {
        $stmt = $this->pdo->prepare('DELETE FROM tasks WHERE id = ?');
        $stmt->execute([$id]);
        return $stmt->rowCount() === 1;
    }

    /** @return array{open: int, done: int} */
    public function stats(): array
    {
        $row = $this->pdo->query(
            'SELECT SUM(done = 0) AS open, SUM(done = 1) AS done FROM tasks'
        )->fetch(PDO::FETCH_ASSOC);
        return ['open' => (int) $row['open'], 'done' => (int) $row['done']];
    }
}

$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$repo = new TaskRepository($pdo);

$a = $repo->add('Plan trip');
$b = $repo->add('Renew passport');
$c = $repo->add('Buy sunscreen');
$repo->complete($b);
$repo->remove($c);

echo json_encode($repo->stats()), "\n";
{"open":1,"done":1}

Test yourself

What happens if you run DELETE FROM tasks without a WHERE clause?

  1. Nothing, PDO refuses it
  2. Only the last row is deleted
  3. Every row in the table is deleted
  4. The table itself is dropped

After $stmt->execute() on an UPDATE, which method tells you how many rows changed?

  1. $pdo->lastInsertId()
  2. $stmt->rowCount()
  3. $stmt->fetchColumn()
  4. count($stmt)

How should a user-chosen sort column be handled?

  1. Bind it with a placeholder
  2. Escape it with addslashes()
  3. Check it against an allow-list of known column names
  4. Wrap it in quotes