Insert, Update, Delete: Writing Data

Insert, Update, Delete: Writing Data in PHP: --- Picture the goods-in bay of a warehouse with a clerk keeping a stock ledger.


The Analogy: The Warehouse Goods-In and Stock Ledger

Picture the goods-in bay of a warehouse with a clerk keeping a stock ledger. When a pallet arrives, the clerk writes a new line in the ledger: a fresh row with the next sequential entry number, the product name, and the quantity. That entry number is assigned by the ledger itself, not by the delivery driver -- the driver never decides which line number their pallet gets. An INSERT is exactly this: you supply the goods, and the database assigns the id, which you then read back with lastInsertId.

When stock is counted or a product is repriced, the clerk does not tear out the ledger line and rewrite the whole thing. They find the existing entry by its number and amend just the changed columns -- the quantity, say -- leaving name and entry number untouched. That is an UPDATE with a WHERE clause: it targets specific rows by a key and changes only the named fields. Crucially, the clerk notes how many lines were amended, because "I updated three entries" is very different from "I found no matching entry to amend".

When goods leave for good -- damaged, expired, recalled -- the clerk strikes the line out of the active ledger. A DELETE with a WHERE clause removes matching rows, and again the count of struck lines tells the clerk whether the strike-out hit anything. A conscientious clerk always reads that count back: a deletion that removed zero lines usually means the entry number was wrong, and pretending it succeeded hides a real mistake.

The catastrophe every warehouse clerk fears is the WHERE-less pen stroke. An UPDATE with no WHERE reprices every product in the ledger to the same figure; a DELETE with no WHERE strikes out the entire stock list in one sweep. The clause that scopes the change is the only thing standing between a routine amendment and wiping the whole ledger. Forget it, and one careless line of SQL rewrites or erases everything, with no pallet-by-pallet undo.


Syntax or Core Structure

The three writing verbs share the prepared-statement rhythm. INSERT adds a row and lastInsertId reports the assigned key. UPDATE and DELETE change or remove rows, and rowCount reports how many were affected.

<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT, done INTEGER DEFAULT 0)');

$ins = $pdo->prepare('INSERT INTO notes (title) VALUES (?)');
$ins->execute(['Buy milk']);
$firstId = (int) $pdo->lastInsertId();
$ins->execute(['Call Ada']);
$secondId = (int) $pdo->lastInsertId();
echo "new ids: $firstId, $secondId\n";

$upd = $pdo->prepare('UPDATE notes SET done = 1 WHERE id = ?');
$upd->execute([$firstId]);
echo 'rows updated: ', $upd->rowCount(), "\n";

$del = $pdo->prepare('DELETE FROM notes WHERE done = ?');
$del->execute([0]);
echo 'rows deleted: ', $del->rowCount(), "\n";

echo 'remaining: ', $pdo->query('SELECT COUNT(*) FROM notes')->fetchColumn(), "\n";

Output:

new ids: 1, 2
rows updated: 1
rows deleted: 1
remaining: 1

Two inserts assign ids 1 and 2, each read back immediately with lastInsertId. The update marks note 1 as done and reports one affected row. The delete removes every still-open note -- only note 2, since note 1 is now done -- so rowCount is 1 and one note remains. Every value is bound, never concatenated, and every change is scoped by a WHERE clause.


Technical Depth: Affected Rows, Upserts, and Safety

What rowCount actually tells you

rowCount returns the number of rows the statement matched and changed. For a DELETE this is the number removed; for an UPDATE it is the number of rows that matched the WHERE clause. A count of zero means the clause matched nothing -- often a sign the key was wrong -- which is exactly the signal you want to check.

StatementrowCount meanslastInsertId
INSERTRows addedThe new key
UPDATERows matched by WHERENot applicable
DELETERows removedNot applicable
<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->exec('CREATE TABLE t (id INTEGER PRIMARY KEY, v INTEGER)');
$pdo->exec('INSERT INTO t (id, v) VALUES (1, 10), (2, 20)');

$u = $pdo->prepare('UPDATE t SET v = ? WHERE id = ?');
$u->execute([99, 1]);
echo 'matched id 1: ', $u->rowCount(), "\n";

$u->execute([50, 999]);
echo 'matched id 999: ', $u->rowCount(), "\n";

Output:

matched id 1: 1
matched id 999: 0

The first update targets an existing row and reports one match. The second targets id 999, which does not exist, so nothing changes and rowCount is 0. Checking this count lets you tell the caller "no such record" instead of falsely reporting success. Note that on some drivers an update that matches a row but sets it to its current value may report 0; know your driver's behaviour before relying on the count for logic.

Upsert: insert or update in one statement

A common need is "add this row, or if it already exists, adjust it". Rather than a fragile select-then-branch, modern databases offer an atomic upsert. In SQLite and PostgreSQL the form is INSERT ... ON CONFLICT ... DO UPDATE.

<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE tally (word TEXT PRIMARY KEY, hits INTEGER NOT NULL)');

$up = $pdo->prepare(
    'INSERT INTO tally (word, hits) VALUES (:w, 1)
     ON CONFLICT(word) DO UPDATE SET hits = hits + 1'
);
foreach (['red', 'blue', 'red', 'red', 'blue'] as $w) {
    $up->execute([':w' => $w]);
}
foreach ($pdo->query('SELECT word, hits FROM tally ORDER BY word') as $row) {
    echo $row['word'], ' = ', $row['hits'], "\n";
}

Output:

blue = 2
red = 3

The first time a word appears, the INSERT succeeds with a count of 1. On every later appearance the primary-key conflict triggers the DO UPDATE, incrementing hits instead. After processing the five words, red has been seen three times and blue twice, in a single statement per word with no read-modify-write race. The exact syntax differs by database -- MySQL uses ON DUPLICATE KEY UPDATE -- but the atomic intent is the same.

Inserting many rows in one statement

Executing a single-row INSERT in a loop works, but a multi-row INSERT -- one statement with several tuples of placeholders -- is markedly faster because it makes one round trip to the database instead of many. You build (?, ?), (?, ?), ... with one tuple per row, then pass a single flat list of values.

<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$pdo->exec('CREATE TABLE readings (id INTEGER PRIMARY KEY, sensor TEXT, value INTEGER)');

$rows = [
    ['A', 21],
    ['B', 19],
    ['A', 23],
    ['C', 25],
];
$tuples = implode(', ', array_fill(0, count($rows), '(?, ?)'));
$sql    = "INSERT INTO readings (sensor, value) VALUES $tuples";
$stmt   = $pdo->prepare($sql);

$flat = [];
foreach ($rows as $r) {
    $flat[] = $r[0];
    $flat[] = $r[1];
}
$stmt->execute($flat);

echo 'inserted: ', $stmt->rowCount(), "\n";
echo 'total: ', $pdo->query('SELECT COUNT(*) FROM readings')->fetchColumn(), "\n";
echo 'sum: ', $pdo->query('SELECT SUM(value) FROM readings')->fetchColumn(), "\n";

Output:

inserted: 4
total: 4
sum: 88

array_fill produces one (?, ?) tuple per row, joined into the VALUES list, and the row values are flattened into one ordered array for execute. All four readings land in a single statement, rowCount reports 4, and the values sum to 88. Only the tuple placeholders are built into the SQL; every actual value is bound, so the batch stays injection-safe. For very large batches, wrapping the insert in a transaction (the next lesson) is faster still.

The WHERE clause is not optional

The most dangerous mistake in this whole topic is omitting WHERE. UPDATE tasks SET done = 1 marks every task done; DELETE FROM tasks empties the table. There is no confirmation prompt and no automatic undo. Always write the WHERE clause first, test the same condition with a SELECT to see which rows it touches, and only then run the destructive statement.


Real World Example: A Task List Manager

Bringing the three verbs together, a TaskList class wraps a tasks table and exposes add, complete, remove, and openCount. Each mutating method returns a boolean or an id derived from rowCount or lastInsertId, so the caller can tell whether the operation actually changed anything.

<?php
declare(strict_types=1);

final class TaskList
{
    public function __construct(private PDO $pdo)
    {
        $this->pdo->exec(
            'CREATE TABLE tasks (
                id    INTEGER PRIMARY KEY,
                title TEXT NOT NULL,
                done  INTEGER NOT NULL DEFAULT 0
            )'
        );
    }

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

    public function complete(int $id): bool
    {
        $stmt = $this->pdo->prepare('UPDATE tasks SET done = 1 WHERE id = ? AND done = 0');
        $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;
    }

    public function openCount(): int
    {
        return (int) $this->pdo->query('SELECT COUNT(*) FROM tasks WHERE done = 0')->fetchColumn();
    }
}

$pdo = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$list = new TaskList($pdo);

$a = $list->add('Write report');
$b = $list->add('Book flights');
$c = $list->add('Renew licence');
echo "added ids: $a, $b, $c\n";
echo 'open: ', $list->openCount(), "\n";

echo 'complete b: ', $list->complete($b) ? 'yes' : 'no', "\n";
echo 'complete b again: ', $list->complete($b) ? 'yes' : 'no', "\n";
echo 'open: ', $list->openCount(), "\n";

echo 'remove c: ', $list->remove($c) ? 'yes' : 'no', "\n";
echo 'remove 999: ', $list->remove(999) ? 'yes' : 'no', "\n";
echo 'open: ', $list->openCount(), "\n";

Output:

added ids: 1, 2, 3
open: 3
complete b: yes
complete b again: no
open: 2
remove c: yes
remove 999: no
open: 1

Three tasks are added, each returning its assigned id, and the open count starts at three. Completing task b succeeds the first time and returns yes; the second attempt matches nothing -- the AND done = 0 guard excludes the already-done row -- so rowCount is 0 and it returns no, which is exactly right for an idempotent complete. Removing task c succeeds, while removing the non-existent id 999 correctly returns no. The final open count is one, the still-open "Write report".

The design flaw is that remove is a hard delete: the row is gone, and with it any history of the task ever existing. In a real application this is often the wrong default. A user who deletes a task by accident cannot recover it, an audit asking "what tasks were completed last quarter" cannot see removed ones, and a foreign key elsewhere pointing at that task id is now dangling. The common fix is a soft delete -- a deleted_at timestamp column that remove sets instead of issuing a real DELETE, with every query filtering out soft-deleted rows. That preserves history and referential integrity at the cost of a little query discipline, a trade most systems handling meaningful data should make deliberately rather than defaulting to irreversible deletion.


Common Mistakes

  1. Omitting the WHERE clause on UPDATE or DELETE. A missing clause changes or erases every row in the table. Always scope the statement, and preview the condition with a SELECT first.
  1. Ignoring rowCount. Treating every UPDATE or DELETE as a success hides the case where the key matched nothing. Check the count so "no such record" is not silently reported as done.
  1. Reading lastInsertId after other statements. The value reflects the most recent insert on that connection. Read it immediately after the INSERT, before any further queries change it.
  1. Assuming lastInsertId works for every table. It relies on an auto-increment or sequence. For tables with a manually assigned or composite key it may return nothing useful.
  1. Doing select-then-insert instead of an upsert. Checking existence and then inserting is a race: two requests can both see "not present" and both insert. Use an atomic ON CONFLICT upsert or a unique constraint.
  1. Hard-deleting data that needs history. A real DELETE destroys audit trails and can leave dangling references. Consider a soft-delete column when the record has downstream meaning.
  1. Forgetting that an update to the same value may report zero. On some drivers an UPDATE that matches a row but changes nothing returns 0. Do not build "record exists" logic solely on a non-zero count without knowing your driver.
  1. Building the SET list from raw input. Splicing column names or values from user input into the SQL reopens injection. Whitelist columns in code and bind all values.
  1. Mutating in a loop without a transaction. A hundred separate INSERT statements each commit individually, which is slow and non-atomic. Wrap a batch in a transaction so it is fast and all-or-nothing.

Best Practices

  • Write the WHERE clause before the SET or the verb, and confirm which rows it matches with a SELECT before running a destructive statement.
  • Read lastInsertId immediately after the INSERT, and treat it as connection-scoped state that later queries can overwrite.
  • Inspect rowCount after every UPDATE and DELETE, using it to distinguish a real change from a no-op or a missing key.
  • Prefer an atomic upsert -- ON CONFLICT DO UPDATE or the driver equivalent -- over a select-then-write sequence that can race.
  • Guard idempotent updates with a condition like AND done = 0, so repeating the operation is safe and reports honestly.
  • Choose soft deletion for records with history, audit, or referential importance, filtering soft-deleted rows in every query.
  • Whitelist any dynamic column names in your own code, and bind every value, so no part of the mutation comes from raw input.
  • Wrap multi-row writes in a transaction so the batch is both faster and atomic, a topic the next lesson develops fully.

Practice Exercises

  1. Create a contacts table, insert three rows with a single reused prepared statement, and print each assigned id from lastInsertId right after its insert.
  1. Write an UPDATE that renames a contact by id, and print rowCount for both an existing id and a non-existent one to show the difference between a match and a no-op.
  1. Implement a page-view counter using an ON CONFLICT DO UPDATE upsert on a page primary key, run it several times for two pages, and print the final counts.
  1. Convert a hard-delete method into a soft delete: add a deleted_at column, change remove to set it, and write a listActive query that excludes soft-deleted rows. Demonstrate that a removed row disappears from listActive but still exists in the table.