How can the code snippet improve error handling for database connections in PHP?
When working with database connections in PHP, it's important to handle errors effectively to prevent unexpected issues. One way to improve error handling is by using try-catch blocks to catch any exceptions that may occur during the connection process. This allows you to gracefully handle errors and provide meaningful error messages to the user.
<?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();
}
?>