PHP Code Examples

Use Database Transactions with PHP PDO

Wrap related database changes in a transaction so they either all succeed or are rolled back.

Example

<?php
try {
    $pdo->beginTransaction();

    $debit = $pdo->prepare(
        'UPDATE accounts SET balance = balance - :amount WHERE id = :id'
    );
    $debit->execute(['amount' => $amount, 'id' => $fromAccountId]);

    if ($debit->rowCount() !== 1) {
        throw new RuntimeException('Source account was not updated.');
    }

    $credit = $pdo->prepare(
        'UPDATE accounts SET balance = balance + :amount WHERE id = :id'
    );
    $credit->execute(['amount' => $amount, 'id' => $toAccountId]);

    if ($credit->rowCount() !== 1) {
        throw new RuntimeException('Destination account was not updated.');
    }

    $pdo->commit();
} catch (Throwable $exception) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    throw $exception;
}

Explanation

A transaction groups multiple statements into one unit of work. If an operation fails, rollback prevents a partially completed update.

Use transactional storage engines such as InnoDB. Validate balances and authorization, and consider row locking for concurrent financial operations.

Share this page Help other developers discover this resource.