PHP Development

PHP PDO MySQL Tutorial: Prepared Statements, Transactions & Error Handling

Master PHP Data Objects (PDO). Learn how to configure robust error handling, write secure prepared statements, and manage ACID database transactions.

2. Recommended PDO Connection Configuration

<?php
$dsn = 'mysql:host=127.0.0.1;dbname=aureviafin_db;charset=utf8mb4';
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false, // Enforce native engine prepares
];

try {
    $pdo = new PDO($dsn, 'db_user', 'secure_password', $options);
} catch (PDOException $e) {
    error_log('Database connection error: ' . $e->getMessage());
    die('Database connection failure. Please contact administrator.');
}

4. Managing Multi-Table ACID Transactions

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

    // Deduct source account balance
    $stmt1 = $pdo->prepare('UPDATE accounts SET balance = balance - :amount WHERE id = :source_id');
    $stmt1->execute([':amount' => 500.00, ':source_id' => 14]);

    // Credit destination account balance
    $stmt2 = $pdo->prepare('UPDATE accounts SET balance = balance + :amount WHERE id = :dest_id');
    $stmt2->execute([':amount' => 500.00, ':dest_id' => 29]);

    // Commit both operations simultaneously
    $pdo->commit();
} catch (Throwable $e) {
    // If any step fails, roll back completely
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    throw $e;
}

Key Takeaways

  • Always set PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION for reliable error handling.
  • Turn off emulated prepares to ensure native database parameter binding.
  • Wrap multi-step database mutations inside transactions with explicit rollback catch blocks.
Marcus Thorne

Marcus Thorne

Head of Technology & Web Engineering

Marcus is a full-stack engineer and educator who has architected fintech payment gateways, secure authentication engines, and performant data pipelines using modern PHP and MySQL.

Editorial Transparency & Disclaimer: The educational content published on AureviaFin is researched and authored independently. It does not constitute individualized financial, investment, or legal counsel. See our full Financial Disclaimer and Editorial Policy.