How can the code snippet be optimized or improved to handle errors more effectively and provide better error messaging to users?

The code snippet can be optimized by implementing try-catch blocks to handle errors more effectively and provide better error messaging to users. By catching specific exceptions and displaying custom error messages, users will have a clearer understanding of what went wrong.

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