Commit every dependent change together or roll all of them back.
Build a Complete Mental Model
PDO prepared statements separate parameters from SQL code. Wrap dependent writes or deletes in a transaction, committing on success and rolling back on failure while accounting for driver limitations and DDL implicit commits.
Apply It in Real PHP
Run and test an original PDO, Prepared Statements & Transactions example with normal, boundary, invalid, and failure inputs, recording output, warnings, exceptions, and side effects.
After This Lesson
<?php
$pdo->beginTransaction();
try {
$sql = 'UPDATE accounts SET balance = balance + :change WHERE id = :id';
$statement = $pdo->prepare($sql);
$statement->execute(['change' => -100, 'id' => 1]);
$statement->execute(['change' => 100, 'id' => 2]);
$pdo->commit();
} catch (Throwable $error) {
if ($pdo->inTransaction()) $pdo->rollBack();
throw $error;
}Both updates commit, or neither does.Try It Yourself
Run and test an original PDO, Prepared Statements & Transactions example with normal, boundary, invalid, and failure inputs, recording output, warnings, exceptions, and side effects.
Security and Common Mistake
Do not assume an exception automatically rolls back a transaction; roll it back explicitly.
PDO Prepared Statements — PHP Documentation Group