Skip to main content

Lesson 3 of 7

Transactions - Atomic Operations

A transaction is a group of database operations that must all succeed or all fail together - atomicity. Without transactions, a crash mid-way through a multi-step operation leaves the database in an inconsistent state. Every operation that touches multiple tables or requires rollback capability needs a transaction.

13 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

PDO Transactions - Commit & Rollback

PDO Transactions - Commit & Rollback
<?php
declare(strict_types=1);

class PostPublishingService {
    public function __construct(private readonly PDO $pdo) {}

    public function publishPost(int $postId, int $editorId): void {
        // These three operations must ALL succeed or ALL fail:
        // 1. Update post status to published
        // 2. Insert audit log entry
        // 3. Update author's published_count stat

        $this->pdo->beginTransaction();
        try {
            // Step 1
            $stmt = $this->pdo->prepare(
                "UPDATE posts SET status = 'published', published_at = UTC_TIMESTAMP()
                 WHERE id = :id AND status = 'draft'"
            );
            $stmt->execute([":id" => $postId]);
            if ($stmt->rowCount() === 0) {
                throw new RuntimeException("Post $postId not found or not in draft state.");
            }

            // Step 2 - audit log
            $stmt = $this->pdo->prepare(
                "INSERT INTO audit_log (action, entity_type, entity_id, user_id, created_at)
                 VALUES ('publish', 'post', :post_id, :editor_id, UTC_TIMESTAMP())"
            );
            $stmt->execute([":post_id" => $postId, ":editor_id" => $editorId]);

            // Step 3 - update stats
            $stmt = $this->pdo->prepare(
                "UPDATE user_stats SET published_count = published_count + 1
                 WHERE user_id = (SELECT author_id FROM posts WHERE id = :id)"
            );
            $stmt->execute([":id" => $postId]);

            $this->pdo->commit();   // ALL succeeded

        } catch (Throwable $e) {
            $this->pdo->rollBack();  // ANY failure - undo everything
            error_log("publishPost failed for post $postId: " . $e->getMessage());
            throw new RuntimeException("Failed to publish post. Please try again.", 0, $e);
        }
    }

    // ── Transfer with deadlock retry ─────────────────────────
    public function transferFunds(int $fromId, int $toId, float $amount, int $retries = 3): void {
        while ($retries > 0) {
            try {
                $this->pdo->beginTransaction();

                $stmt = $this->pdo->prepare("SELECT balance FROM accounts WHERE id = :id FOR UPDATE");
                $stmt->execute([":id" => $fromId]);
                $balance = (float) $stmt->fetchColumn();

                if ($balance < $amount) {
                    $this->pdo->rollBack();
                    throw new RuntimeException("Insufficient funds.");
                }

                $this->pdo->prepare("UPDATE accounts SET balance = balance - :amt WHERE id = :id")
                    ->execute([":amt" => $amount, ":id" => $fromId]);
                $this->pdo->prepare("UPDATE accounts SET balance = balance + :amt WHERE id = :id")
                    ->execute([":amt" => $amount, ":id" => $toId]);

                $this->pdo->commit();
                return;

            } catch (PDOException $e) {
                $this->pdo->rollBack();
                if (str_contains($e->getMessage(), "Deadlock") && --$retries > 0) {
                    usleep(100_000);  // wait 100ms then retry
                    continue;
                }
                throw $e;
            }
        }
    }
}

Quick Quiz

Tip

Tip

Practice Transactions Atomic Operations in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Transactions - Atomic Operations

Practice Task

Note

Practice Task - (1) Write a working example of Transactions Atomic Operations from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Transactions Atomic Operations is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done