SyntaxStudy
Sign Up
PHP Intermediate 5 min read

PDO Transactions

PDO Transactions

Transactions group multiple queries into an atomic unit — either all succeed or all are rolled back. Use them for operations that must be consistent.

Example
<?php
$pdo->beginTransaction();

try {
    // Debit account A
    $pdo->prepare("UPDATE accounts SET balance = balance - :amount WHERE id = :id")
        ->execute(["amount" => $amount, "id" => $fromId]);

    // Credit account B
    $pdo->prepare("UPDATE accounts SET balance = balance + :amount WHERE id = :id")
        ->execute(["amount" => $amount, "id" => $toId]);

    $pdo->commit();
    echo "Transfer complete";
} catch (PDOException $e) {
    $pdo->rollBack();
    throw new RuntimeException("Transfer failed: " . $e->getMessage(), 0, $e);
}
Pro Tip

Always call rollBack() in the catch block when using transactions — uncommitted transactions are rolled back automatically when the script ends, but be explicit.