← Back to Chapters

PHP PDO – Transactions

? PHP PDO – Transactions

? Quick Overview

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.

? Key Concepts

  • Transactions group multiple SQL statements together
  • All operations succeed or all are rolled back
  • Essential for financial and multi-step operations

? Syntax & Theory

PDO uses three main methods for transactions: beginTransaction(), commit(), and rollBack(). These help enforce ACID properties in database systems.

? Code Example

? View Code Example
// 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();
}
?>

? Live Output / Explanation

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().

? Interactive Concept

Think of a transaction like a safety net: if one step breaks, everything resets to the original state.

? Use Cases

  • Bank transfers
  • Order placement systems
  • Inventory updates

✅ Tips & Best Practices

  • Always use try-catch blocks
  • Keep transactions short
  • Rollback immediately on failure

? Try It Yourself

  • Update account balance and log transaction together
  • Force an error to test rollback behavior
  • Build a checkout process using transactions