Codectionary / Developer documentation / PHP

Commit or Roll Back Work with PDO Transactions

Group related database changes and handle failures using a private in-memory SQLite example.

What it is and why to use it

When two database updates form one logical operation, keeping only the first can leave inconsistent data. A transaction groups supported database work so it can be committed together or rolled back on failure. PDO exposes beginTransaction(), commit() and rollBack(), but the database driver and storage engine determine the actual transaction capabilities and isolation behaviour.

How it works

Create the schema and demonstration data first, then begin a transaction before the related updates. Commit only after every required operation succeeds. Catch Throwable at this local operation boundary, roll back if inTransaction() is true, and return a controlled failure or rethrow appropriately. The examples use SQLite :memory:, which creates a database private to that connection and discards it when the process ends.

Common mistakes and limitations

A transaction does not make arbitrary read-then-write logic safe against all concurrency races. Check affected rows and use suitable constraints, locking or atomic updates for real systems. Some databases implicitly commit around schema changes, so do not assume DDL can always be rolled back. Database rollback cannot undo email, file writes or other external side effects.

Run the examples locally

Save each complete example in its own example.php file and run php example.php in a terminal from that folder. Each example is independent: do not paste both into one file, especially when they declare classes with the same names. Output appears in the terminal. The examples use PHP 8.0-compatible syntax; use a currently supported PHP release for development.

The <?php opening tag starts PHP code. declare(strict_types=1) requests strict scalar argument checks for function calls made from this file; it does not validate external input for you. echo writes output, and PHP_EOL adds the platform’s line ending. Quotation marks delimit strings; they are not part of the printed text unless explicitly included in the string.

These two examples require PDO and the PDO_SQLITE driver; check php -m and enable the appropriate extension if needed. They use sqlite::memory: only: no database server, credentials, persistent database file or Codectionary backend is contacted. Error mode is set explicitly to exceptions.

Check your interpreter, lint and run one saved example

php -v
php -l example.php
php example.php

Continue learning

Use the related guides to connect this operation to the surrounding language features. Practise by changing the example inputs and predicting the output before running it.

Syntax

$pdo->beginTransaction();
// related statements
$pdo->commit(); // or rollBack() on failure

Examples

Commit two related updates

Move twenty demonstration points between two rows in an isolated database.

<?php
declare(strict_types=1);

$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE points (id INTEGER PRIMARY KEY, balance INTEGER NOT NULL)');
$pdo->exec('INSERT INTO points (id, balance) VALUES (1, 100), (2, 50)');
$pdo->beginTransaction();
try {
    $change = $pdo->prepare('UPDATE points SET balance = balance + ? WHERE id = ?');
    $change->execute([-20, 1]);
    $change->execute([20, 2]);
    $pdo->commit();
} catch (Throwable $error) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    throw $error;
}
foreach ($pdo->query('SELECT id, balance FROM points ORDER BY id') as $row) {
    echo $row['id'], ': ', $row['balance'], PHP_EOL;
}
  1. The schema and seed rows are created before beginning the transaction; all data lives in the private connection.
  2. One prepared update statement is executed with different parameter values to subtract from row 1 and add to row 2.
  3. commit retains both updates. The catch rolls back a failed transaction and rethrows rather than falsely reporting success.
  4. The ordered query prints both final balances. This is a transaction demonstration, not a complete concurrent transfer system with row checks, nonnegative constraints or retry rules.
  5. Expected output: 1: 80 2: 70

Roll back a partial operation

Simulate an application failure after an update and verify the original value is restored.

<?php
declare(strict_types=1);

$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE points (id INTEGER PRIMARY KEY, balance INTEGER NOT NULL)');
$pdo->exec('INSERT INTO points (id, balance) VALUES (1, 100)');
$pdo->beginTransaction();
try {
    $change = $pdo->prepare('UPDATE points SET balance = balance - ? WHERE id = ?');
    $change->execute([20, 1]);
    throw new RuntimeException('Simulated second-step failure');
    $pdo->commit();
} catch (Throwable $error) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    echo 'Operation cancelled', PHP_EOL;
}
echo $pdo->query('SELECT balance FROM points WHERE id = 1')->fetchColumn(), PHP_EOL;
  1. The update temporarily changes the balance inside the transaction.
  2. The deliberate exception skips commit and enters the catch block.
  3. rollBack undoes the update, so the final query reads 100. The generic cancellation message avoids exposing the raw failure as a public response.
  4. The unreachable commit marks the normal success path if the simulated failure were removed. Real code must handle and report failure consistently at its own boundary.
  5. Expected output: Operation cancelled 100

Best practices

  • Keep transactions short and choose database-specific concurrency rules.
  • Keep schema setup outside the demonstrated transaction and handle rollback explicitly.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading