phpPHP
Module 28: PDO – AdvancedIntermediate50 min read

Advanced PDO: Fetch Modes, Atomic Transactions & Repository Pattern

Master PDO fetch modes (FETCH_ASSOC, FETCH_CLASS, FETCH_KEY_PAIR), beginTransaction/commit/rollBack atomic workflows, and clean Repository abstraction.

Key Takeaways & Core Concepts
  • Master PDO fetch modes (FETCH_ASSOC, FETCH_CLASS, FETCH_KEY_PAIR), beginTransaction/commit/rollBack atomic workflows, and clean Repository abstraction.
  • Practice writing and running standard examples.
  • Apply best practices and debugging techniques.

Advanced PDO: Fetch Modes, Atomic Transactions & Repository Pattern

### 1. Atomic Transactions Wrap multi-step financial or inventory updates in $pdo->beginTransaction() ... $pdo->commit(), with $pdo->rollBack() inside catch (Throwable $e) so partial writes never corrupt state!

1. Atomic Transfer Transaction Blueprint
1<?php
2function transferBlueprint(PDO $pdo, int $from, int $to, float $amt): void {
3 $pdo->beginTransaction();
4 try {
5 $pdo->prepare("UPDATE accounts SET bal = bal - ? WHERE id = ?")->execute([$amt, $from]);
6 $pdo->prepare("UPDATE accounts SET bal = bal + ? WHERE id = ?")->execute([$amt, $to]);
7 $pdo->commit();
8 } catch (Throwable $e) {
9 $pdo->rollBack();
10 throw $e;
11 }
12}
13echo "Transaction blueprint ready.\n";
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
13 lines
Note: Ensures debit and credit succeed or roll back together atomically.
Practice & AssessmentPHP Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)