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

PHP Error Handling in DB

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 {
    $pdo = new PDO('sqlite::memory:');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec("SELECT * FROM missing_table");
} catch (PDOException $e) {
    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
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
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 {
    $pdo = new PDO('sqlite::memory:');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec("SELECT * FROM missing_table");
} catch (PDOException $e) {
    error_log($e->getMessage());
    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 {
    $pdo = new PDO('sqlite::memory:');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec("SELECT * FROM missing_table");
} catch (PDOException $e) {
    error_log("DB error: " . $e->getMessage());
    echo "Logged for developers, hidden from the visitor.";
}
?>

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.