← Back to PHP Course | Chapter 11: Database | Lesson 8 of 21

PHP Error Handling in DB

Database error handling is about being ready when things go wrong, like having a plan if the school bus breaks down. PHP catches the problem and responds politely instead of crashing.
Syntax
php
try {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->query("SQL statement");
} catch (PDOException $e) {
    error_log($e->getMessage());   // log details, show a friendly message
}

Catching Database Exceptions

Database operations can fail for many reasons — a lost connection, a constraint violation, a syntax error in a query — and how your code reacts to those failures determines whether a user sees a clear message or a broken page.

Example: Catching Database Exceptions

php
<?php
// Try running this block; jump to `catch` if it throws
try {
    // Create a new `PDO` instance with 'sqlite::memory:', stored in `$pdo`
    $pdo = new PDO('sqlite::memory:');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec("SELECT * FROM missing_table");
// Catch PDOException $e
} catch (PDOException $e) {
    // Print "A clear error was caught instead of a broken page" to the output
    echo "A clear error was caught instead of a broken page";
}
?>

Reading Error Codes

Setting PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION (or checking mysqli_error() after each mysqli call) ensures database failures surface immediately instead of being silently ignored and causing confusing bugs downstream.

Example: Reading Error Codes

php
<?php
// Create a new `PDO` instance with 'sqlite::memory:', stored in `$pdo`
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Print "Errors will now surface immediately as exceptions" to the output
echo "Errors will now surface immediately as exceptions";
?>

Custom Error Loggers

Wrapping database calls in a try/catch block lets you catch a PDOException specifically, log the technical details for developers, and show the end user a friendly, non-technical error message instead.

Example: Custom Error Loggers

php
<?php
// Try running this block; jump to `catch` if it throws
try {
    // Create a new `PDO` instance with 'sqlite::memory:', stored in `$pdo`
    $pdo = new PDO('sqlite::memory:');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec("SELECT * FROM missing_table");
// Catch PDOException $e
} catch (PDOException $e) {
    // Call `error_log($e->getMessage())`
    error_log($e->getMessage());
    // Print "Something went wrong. Please try again." to the output
    echo "Something went wrong. Please try again.";
}
?>

MySQLi Connection Errors

Never display raw database error messages directly to end users — they can leak details about your schema or query structure that an attacker could use, and are generally meaningless to a non-technical visitor anyway.

Example: MySQLi Connection Errors

php
<?php
try {
    $pdo = new PDO('sqlite::memory:');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec("SELECT * FROM missing_table");
} catch (PDOException $e) {
    // Never echo $e->getMessage() directly to the visitor -- it can leak schema details
    echo "An error occurred.";
}
?>

Suppressing Sensitive Details

Logging the full exception (including the query and parameters, but never raw passwords) to a server-side log file gives you the detail you need to debug an issue without exposing anything sensitive to the public.

Example: Suppressing Sensitive Details

php
<?php
// Try running this block; jump to `catch` if it throws
try {
    // Create a new `PDO` instance with 'sqlite::memory:', stored in `$pdo`
    $pdo = new PDO('sqlite::memory:');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec("SELECT * FROM missing_table");
// Catch PDOException $e
} catch (PDOException $e) {
    // Call `error_log("DB error: " . $e->getMessage())`
    error_log("DB error: " . $e->getMessage());
    // Print "Logged for developers, hidden from the visitor." to the output
    echo "Logged for developers, hidden from the visitor.";
}
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Showing raw database error messages to visitors, which can leak table names and credentials.
  2. Not catching PDOException when PDO is set to throw exceptions, so the script ends with a fatal error.
  3. Ignoring the error code, so different failures such as a duplicate key are all treated the same.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.