What are the best practices for error handling and displaying error messages in PHP code, especially when dealing with database connections?

When handling errors in PHP code, especially when dealing with database connections, it is important to use try-catch blocks to catch exceptions and display meaningful error messages to the user. This helps in troubleshooting and debugging issues more effectively. Additionally, using error logging functions like error_log() can help in tracking errors in the backend.

try {
    $db = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
} catch (PDOException $e) {
    error_log("Connection failed: " . $e->getMessage());
    echo "Database connection error. Please try again later.";
}