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.