Skip to content
PHP Logo

Are there any best practices or recommended approaches for displaying and handling errors in PHP scripts, particularly when dealing with database-related errors?

When handling database-related errors in PHP scripts, it is essential to display user-friendly error messages while also logging detailed information for debugging purposes. One common approach is to use try-catch blocks to catch exceptions thrown by database operations and then display an appropriate error message to the user. Additionally, logging the error details to a log file or database can help in troubleshooting and resolving issues efficiently.

php
try {
    // Database connection and query execution
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->execute(array(':id' => $user_id));
    
    // Process the query result
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if(!$user) {
        throw new Exception("User not found");
    }
    
    // Display user data or perform other operations
    echo "User Name: " . $user['name'];
    
} catch(PDOException $e) {
    // Display user-friendly error message
    echo "An error occurred. Please try again later.";
    
    // Log detailed error information for debugging
    error_log("Database Error: " . $e->getMessage());
} catch(Exception $e) {
    // Display user-friendly error message for specific exceptions
    echo $e->getMessage();
}