How can error handling be improved in the PHP code provided to troubleshoot database connection issues?

To improve error handling in the PHP code provided to troubleshoot database connection issues, we can add a try-catch block around the database connection code and catch any exceptions that may occur. This will allow us to handle any errors gracefully and provide more informative error messages to aid in troubleshooting.

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

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();
}
?>