What are best practices for handling database connections in PHP to avoid errors like "Unable to connect to server"?

When handling database connections in PHP, it is important to properly handle potential errors such as "Unable to connect to server". One way to avoid this issue is to use try-catch blocks when establishing the database connection. This allows you to catch any exceptions that may occur during the connection process and handle them accordingly.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>