Lesson 17 of 20

PDO Database Access

PDO Basics

PDO (PHP Data Objects) provides a consistent interface for accessing databases. It supports prepared statements, transactions, and multiple database drivers.

Example
<?php
try {
    $pdo = new PDO(
        'mysql:host=localhost;dbname=myapp;charset=utf8mb4',
        'root', '',
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );

    // Prepared statement with named parameters
    $stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)');
    $stmt->execute(['name' => 'Alice', 'email' => 'alice@example.com']);
    $lastId = $pdo->lastInsertId();

    // Query with fetch
    $stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
    $stmt->execute(['id' => $lastId]);
    $user = $stmt->fetch();

    // Fetch all
    $stmt = $pdo->query('SELECT * FROM users');
    $users = $stmt->fetchAll();

    foreach ($users as $user) {
        echo "{$user['name']} - {$user['email']}\n";
    }
} catch (PDOException $e) {
    echo 'Database error: ' . $e->getMessage();
}
?>

Transactions

PDO supports transactions for atomic operations — either all queries succeed or all are rolled back.

Example
<?php
try {
    $pdo->beginTransaction();

    $pdo->prepare('UPDATE accounts SET balance = balance - :amount WHERE id = :from')
        ->execute(['amount' => 100, 'from' => 1]);

    $pdo->prepare('UPDATE accounts SET balance = balance + :amount WHERE id = :to')
        ->execute(['amount' => 100, 'to' => 2]);

    $pdo->commit();
    echo 'Transfer successful!';
} catch (Exception $e) {
    $pdo->rollBack();
    echo 'Transfer failed: ' . $e->getMessage();
}
?>