← Back to Chapters

PHP PDO with Exception Handling

? PHP PDO with Exception Handling

? Quick Overview

PHP PDO supports powerful exception handling mechanisms that help developers catch and manage database-related errors safely using try-catch blocks.

? Key Concepts

  • PDOException class
  • try-catch blocks
  • ERRMODE_EXCEPTION

? Syntax & Theory

By enabling exception mode in PDO, database errors throw exceptions instead of failing silently. This ensures controlled error handling and better debugging.

? Code Example

? View Code Example
// Demonstrates PDO connection and query with exception handling
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->query("SELECT id, name FROM users");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
} catch (PDOException $e) {
echo "Database error: " . $e->getMessage();
}
?>

? Live Output / Explanation

If the database connection or query fails, the script safely displays an error message instead of crashing.

? Interactive Concept

Change the database name intentionally and observe how the exception is triggered and handled gracefully.

? Use Cases

  • Secure database-driven applications
  • Error logging systems
  • Production-grade PHP applications

✅ Tips & Best Practices

  • Always enable PDO::ERRMODE_EXCEPTION.
  • Log errors internally instead of displaying them publicly.
  • Wrap both connection and queries in try-catch blocks.

? Try It Yourself

  • Use a wrong database name to test exception flow.
  • Implement prepared statements with exception handling.
  • Log errors to a file inside the catch block.