How can error handling be improved in the provided PHP code to better troubleshoot database connection issues?
The issue with the provided PHP code is that it lacks proper error handling for database connection issues, making it difficult to troubleshoot problems when they occur. To improve error handling, we can implement try-catch blocks around the database connection code and use the PDOException class to catch and display any errors that may occur during the connection process.
<?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"; // or any other code to execute if connection is successful
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>