Alice and Bob open the same support ticket. Both see version 1. Alice fixes the title and saves first. If Bob later submits an ordinary update by ticket ID, his old form can overwrite Alice's newer work even though the database executes each statement correctly.

This PHP PDO and SQLite example makes the stale edit visible. The update must match both the ticket ID and the version the editor originally loaded. A successful save increments that version in the same statement. Bob's version-1 submission then matches no row, so the application can ask him to compare the changes.

The downloadable project contains all four PHP files, the verifier, this output and setup notes. It uses fictional data in a temporary database and never opens an existing application database.

Requirements and the behavior to expect

Use PHP 8.1 or later from a terminal with PDO and pdo_sqlite enabled. No Composer package, web server or database account is required. The recorded checks ran with PHP 8.2.12 and SQLite 3.39.2 on Windows; those are the available test versions, not a recommendation to use an old PHP patch.

Extract the ZIP, enter its php-optimistic-locking folder and run:

php demo.php
php verify.php

The demo prints:

Both editors loaded version 1.
Alice save: saved
Bob stale save: conflict
Current: version=2 title=Printer cable replaced status=in_progress

The two connections take turns: read, read, Alice saves, Bob attempts a stale save. This deterministic interleaving reproduces the lost-update condition without timing-dependent sleeps or background processes. It does not test parallel load or lock contention.

The version check belongs inside UPDATE

Checking a version with a separate SELECT and then updating only by ID leaves a gap between the check and the write. Here, the WHERE condition and version = version + 1 are part of one statement. SQLite documents that an UPDATE affects only rows satisfying its WHERE expression; matching zero rows is not a SQL error.

Save this complete data-access file as tickets.php. Every submitted value uses a separate placeholder. The PDO prepare documentation explains binding data values rather than putting input directly into SQL.

<?php
declare(strict_types=1);

function openTicketDatabase(string $path): PDO
{
    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ];

    $database = new PDO('sqlite:' . $path, null, null, $options);

    return $database;
}

function readTicket(PDO $database, int $id): ?array
{
    $statement = $database->prepare(
        'SELECT id, title, status, version FROM tickets WHERE id = :id'
    );
    $statement->bindValue(':id', $id, PDO::PARAM_INT);
    $statement->execute();

    $ticket = $statement->fetch();
    $statement->closeCursor();

    if ($ticket === false) {
        return null;
    }

    return $ticket;
}

function saveTicket(
    PDO $database,
    int $id,
    int $expectedVersion,
    string $title,
    string $status
): bool {
    $title = trim($title);
    $allowedStatuses = ['open', 'in_progress', 'closed'];

    if ($id < 1 || $expectedVersion < 1) {
        throw new InvalidArgumentException('ID and version must be positive.');
    }

    if ($title === '' || strlen($title) > 120) {
        throw new InvalidArgumentException('Title must contain 1 to 120 bytes.');
    }

    if (!in_array($status, $allowedStatuses, true)) {
        throw new InvalidArgumentException('Unknown ticket status.');
    }

    $statement = $database->prepare(
        'UPDATE tickets
         SET title = :title, status = :status, version = version + 1
         WHERE id = :id AND version = :expected_version'
    );
    $statement->bindValue(':title', $title, PDO::PARAM_STR);
    $statement->bindValue(':status', $status, PDO::PARAM_STR);
    $statement->bindValue(':id', $id, PDO::PARAM_INT);
    $statement->bindValue(':expected_version', $expectedVersion, PDO::PARAM_INT);
    $statement->execute();

    $saved = $statement->rowCount() === 1;
    $statement->closeCursor();

    return $saved;
}

The result is deliberately small: true means one row accepted the expected version; false means no row matched. That can mean a stale version or a ticket that has been deleted. Database failures remain exceptions instead of being mislabeled as editing conflicts. The title limit is 120 bytes after trimming, not 120 Unicode characters.

PDOStatement::rowCount() reports affected rows for UPDATE. Do not reuse it to count a SELECT result. This example increments the version even when title and status stay the same, so an accepted same-value save still changes the row.

Create an isolated database for each run

Save this as fixture.php. It creates one temporary file, seeds a ticket, opens a second connection and passes both connections to a callback. The connections close before the file is removed in finally. The fixture is teaching infrastructure; use the data-access functions with your own application wiring when adapting the idea.

<?php
declare(strict_types=1);

require_once __DIR__ . '/tickets.php';

function withTicketFixture(callable $action): void
{
    $path = tempnam(sys_get_temp_dir(), 'toolzify-ticket-');

    if ($path === false) {
        throw new RuntimeException('Cannot create a temporary database.');
    }

    $first = null;
    $second = null;

    try {
        $first = openTicketDatabase($path);
        $first->exec(
            "CREATE TABLE tickets (
                id INTEGER PRIMARY KEY,
                title TEXT NOT NULL,
                status TEXT NOT NULL CHECK (status IN ('open', 'in_progress', 'closed')),
                version INTEGER NOT NULL CHECK (version >= 1)
            )"
        );

        $initialTicket = [
            ':id' => 1,
            ':title' => 'Printer is offline',
            ':status' => 'open',
            ':version' => 1,
        ];
        $statement = $first->prepare(
            'INSERT INTO tickets (id, title, status, version)
             VALUES (:id, :title, :status, :version)'
        );
        $statement->execute($initialTicket);
        $statement = null;

        $second = openTicketDatabase($path);
        $action($first, $second);
    } finally {
        $first = null;
        $second = null;

        if (is_file($path) && !unlink($path)) {
            throw new RuntimeException('Cannot remove the temporary database.');
        }
    }
}

There is no explicit read transaction held open while an editor thinks. SQLite's isolation documentation explains its single-writer model and how transactions affect what separate connections see. A version predicate detects stale application data; it does not remove database locks or turn a busy-database exception into a conflict result.

Reproduce the stale submission

Save the following as demo.php. Bob keeps the version from his original read. He does not fetch a fresh version merely to make the outdated write succeed.

<?php
declare(strict_types=1);

require_once __DIR__ . '/fixture.php';

$demonstrateConflict = function (PDO $first, PDO $second): void {
    $alice = readTicket($first, 1);
    $bob = readTicket($second, 1);

    if ($alice === null || $bob === null) {
        throw new RuntimeException('The sample ticket is missing.');
    }

    printf("Both editors loaded version %d.\n", $alice['version']);

    $aliceSaved = saveTicket(
        $first,
        1,
        (int) $alice['version'],
        'Printer cable replaced',
        'in_progress'
    );
    printf("Alice save: %s\n", $aliceSaved ? 'saved' : 'conflict');

    $bobSaved = saveTicket(
        $second,
        1,
        (int) $bob['version'],
        'Printer restarted',
        'closed'
    );
    printf("Bob stale save: %s\n", $bobSaved ? 'saved' : 'conflict');

    $current = readTicket($second, 1);

    if ($current === null) {
        throw new RuntimeException('The sample ticket disappeared.');
    }

    printf(
        "Current: version=%d title=%s status=%s\n",
        $current['version'],
        $current['title'],
        $current['status']
    );
};

withTicketFixture($demonstrateConflict);

After the failed submission, the final read proves that Alice's title, status and version survived. If Bob wants to proceed, show him the current ticket alongside his submitted values and let him deliberately reconcile them. Blindly retrying with the latest version would recreate the overwrite the check was meant to prevent.

Run the verifier and inspect persisted state

The ZIP includes the complete verify.php below. Each case uses a new fixture. It throws on failure instead of depending on PHP's configurable assert() behavior.

<?php
declare(strict_types=1);

require_once __DIR__ . '/fixture.php';

function check(bool $condition, string $message): void
{
    if (!$condition) {
        throw new RuntimeException($message);
    }
}

function expectInvalid(callable $action): void
{
    try {
        $action();
    } catch (InvalidArgumentException $exception) {
        return;
    }

    throw new RuntimeException('Expected InvalidArgumentException.');
}

$cases = [
    'two connections read the same version' => function (PDO $first, PDO $second): void {
        check($first !== $second, 'Expected independent connections.');
        check(readTicket($first, 1) === readTicket($second, 1), 'Initial rows differ.');
    },
    'a current version saves and increments' => function (PDO $first, PDO $second): void {
        check(saveTicket($first, 1, 1, 'Updated', 'in_progress'), 'Save failed.');
        $current = readTicket($second, 1);
        check((int) $current['version'] === 2, 'Version did not advance.');
        check($current['title'] === 'Updated', 'Title did not persist.');
        check($current['status'] === 'in_progress', 'Status did not persist.');
    },
    'a stale save preserves the winning row' => function (PDO $first, PDO $second): void {
        $bob = readTicket($second, 1);
        check(saveTicket($first, 1, 1, 'Winner', 'in_progress'), 'First save failed.');
        $winner = readTicket($first, 1);
        $saved = saveTicket($second, 1, (int) $bob['version'], 'Loser', 'closed');
        check(!$saved, 'Stale update succeeded.');
        check(readTicket($second, 1) === $winner, 'Winning row was overwritten.');
    },
    'a missing ticket does not insert a row' => function (PDO $first, PDO $second): void {
        check(!saveTicket($first, 99, 1, 'Missing', 'open'), 'Missing row saved.');
        check(readTicket($second, 99) === null, 'Missing row was inserted.');
    },
    'a future version does not match' => function (PDO $first, PDO $second): void {
        check(!saveTicket($first, 1, 9, 'Future', 'closed'), 'Future version saved.');
        check((int) readTicket($second, 1)['version'] === 1, 'Row changed.');
    },
    'identical content still advances the version' => function (PDO $first, PDO $second): void {
        check(saveTicket($first, 1, 1, 'Printer is offline', 'open'), 'No-op failed.');
        check((int) readTicket($second, 1)['version'] === 2, 'Version did not advance.');
    },
    'reload and deliberate retry use the new version' => function (PDO $first, PDO $second): void {
        check(saveTicket($first, 1, 1, 'First edit', 'in_progress'), 'First save failed.');
        $fresh = readTicket($second, 1);
        check(saveTicket($second, 1, (int) $fresh['version'], 'Reviewed edit', 'closed'), 'Retry failed.');
        $current = readTicket($first, 1);
        check((int) $current['version'] === 3, 'Wrong final version.');
        check($current['title'] === 'Reviewed edit', 'Retry not persisted.');
    },
    'SQL-like title is stored literally' => function (PDO $first, PDO $second): void {
        $title = "Bob's printer; DROP TABLE tickets; --";
        check(saveTicket($first, 1, 1, $title, 'open'), 'Literal title failed.');
        check(readTicket($second, 1)['title'] === $title, 'Title was not literal.');
    },
    'title whitespace is trimmed' => function (PDO $first, PDO $second): void {
        check(saveTicket($first, 1, 1, '  Trimmed  ', 'open'), 'Trim save failed.');
        check(readTicket($second, 1)['title'] === 'Trimmed', 'Title not trimmed.');
    },
    'empty title is rejected without a write' => function (PDO $first, PDO $second): void {
        $attempt = function () use ($first): void {
            saveTicket($first, 1, 1, '   ', 'open');
        };
        expectInvalid($attempt);
        check((int) readTicket($second, 1)['version'] === 1, 'Invalid input changed row.');
    },
    '120 bytes pass and 121 bytes fail' => function (PDO $first, PDO $second): void {
        check(saveTicket($first, 1, 1, str_repeat('a', 120), 'open'), 'Boundary rejected.');
        $attempt = function () use ($second): void {
            saveTicket($second, 1, 2, str_repeat('a', 121), 'open');
        };
        expectInvalid($attempt);
        check((int) readTicket($first, 1)['version'] === 2, 'Oversize input changed row.');
    },
    'unknown status is rejected without a write' => function (PDO $first, PDO $second): void {
        $attempt = function () use ($first): void {
            saveTicket($first, 1, 1, 'Valid title', 'deleted');
        };
        expectInvalid($attempt);
        check(readTicket($second, 1)['status'] === 'open', 'Invalid status persisted.');
    },
    'zero version is rejected' => function (PDO $first, PDO $second): void {
        $attempt = function () use ($first): void {
            saveTicket($first, 1, 0, 'Valid title', 'open');
        };
        expectInvalid($attempt);
        check((int) readTicket($second, 1)['version'] === 1, 'Zero version changed row.');
    },
    'zero ID is rejected' => function (PDO $first, PDO $second): void {
        $attempt = function () use ($first): void {
            saveTicket($first, 0, 1, 'Valid title', 'open');
        };
        expectInvalid($attempt);
        check((int) readTicket($second, 1)['version'] === 1, 'Zero ID changed row.');
    },
    'database failure throws instead of returning conflict' => function (PDO $first, PDO $second): void {
        $first->exec('DROP TABLE tickets');

        try {
            saveTicket($second, 1, 1, 'Valid title', 'open');
        } catch (PDOException $exception) {
            return;
        }

        throw new RuntimeException('Database error was hidden as a conflict.');
    },
];

$passed = 0;

foreach ($cases as $name => $case) {
    withTicketFixture($case);
    $passed++;
    printf("PASS %s\n", $name);
}

printf("%d tests passed.\n", $passed);

The source project and a separately extracted ZIP each passed all 15 tests and produced the exact demo output shown above. All four PHP files passed syntax checks in both copies. A temporary negative-control copy with the version condition removed failed the stale-save test, confirming that the verifier detects that regression.

CasesObserved result
Independent connections, accepted save and same-value saveThe saved row is visible and its version advances.
Stale version, missing ticket and future versionNo matching write; the existing row is preserved.
Reload and deliberate retryA newly reviewed save advances version 2 to version 3.
SQL-like title and surrounding whitespaceInput is stored literally after trimming.
Empty or oversized title, unknown status, zero ID or versionValidation rejects the input before a write.
Missing database tablePDOException propagates; it is not reported as a stale edit.

Adapting this to a real editor

Carry the loaded version with the submitted edit, validate it on the server and include the current user's authorization constraints in the write. A version number is not permission to edit a row. A web implementation also needs CSRF protection, escaped output and a conflict screen that preserves the submitted text. This project supplies the database behavior, not those web application features.

Every route, job and administrator script that changes these fields must advance the version. A writer that bypasses the rule can make stale edits appear current. Keep versions monotonic for a ticket's lifetime; do not reset them during normal updates. If one logical save changes several tables, combine the conditional update and related writes in a transaction. The separate PDO commit and rollback example demonstrates that boundary.

If PHP says it cannot find the driver, enable pdo_sqlite for the CLI configuration used by your terminal. If the temporary directory is not writable, correct that environment issue before running the fixture. An exception while saving is a different path from a clean false result; handle and log it appropriately instead of telling the editor that somebody else necessarily changed the ticket.