Transaction

A transaction is a sequence of database operations that is treated as a single atomic unit. Either all operations succeed and are committed together, or any failure causes all of them to be rolled back, leaving the database unchanged.

Transactions follow the ACID properties: Atomicity, Consistency, Isolation, and Durability.

Transactions are most commonly used through PDO or database-specific extensions. An explicit transaction starts with beginTransaction(), ends with commit(), and is undone with rollBack().

ORMs such as Doctrine and Eloquent also expose transaction helpers and often wrap operations automatically.

<?php

    $pdo = new PDO('mysql:host=localhost;dbname=shop', 'user', 'pass');

    try {
        $pdo->beginTransaction();

        $pdo->exec("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
        $pdo->exec("UPDATE accounts SET balance = balance + 100 WHERE id = 2");

        $pdo->commit();
    } catch (Throwable $e) {
        $pdo->rollBack();
        throw $e;
    }

?>

Documentation

See also ACID and PDO Transactions and auto-commit.

Related : PHP Data Objects (PDO), Database, Exception, Try-catch, Rollback, Atomic Operation, Database Commit, Race Condition