What are some best practices for handling database errors in PHP code?

When handling database errors in PHP code, it is important to implement error handling to gracefully manage any issues that may arise. One common practice is to use try-catch blocks to catch exceptions thrown by database operations and handle them appropriately, such as logging the error or displaying a user-friendly message.

try {
    // Perform database operations
} catch (PDOException $e) {
    // Handle database errors
    echo "An error occurred: " . $e->getMessage();
    // Log the error
    error_log("Database error: " . $e->getMessage());
}