PDO transactions allow multiple database operations to be executed as a single unit of work. Either all queries succeed or none of them are applied, ensuring reliable and consistent data handling.
PDO uses three main methods for transactions: beginTransaction(), commit(), and rollBack(). These help enforce ACID properties in database systems.
// Demonstrating a PDO transaction with commit and rollback
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=testdb","root","");
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$pdo->beginTransaction();
$pdo->exec("INSERT INTO users (name,email) VALUES ('Alice','alice@example.com')");
$pdo->exec("INSERT INTO users (name,email) VALUES ('Bob','bob@example.com')");
$pdo->commit();
echo "Transaction completed successfully!";
} catch (Exception $e) {
$pdo->rollBack();
echo "Transaction failed: ".$e->getMessage();
}
?>
If both INSERT queries run successfully, the transaction is committed and data is saved. If any query fails, all changes are reverted automatically using rollBack().
Think of a transaction like a safety net: if one step breaks, everything resets to the original state.