What are best practices for error handling in PHP when dealing with database connections?
When dealing with database connections in PHP, it is important to implement error handling to gracefully handle any potential issues that may arise. One common practice is to use try-catch blocks to catch any exceptions that may occur during the connection process and display an appropriate error message to the user.
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
// Use the $pdo object to interact with the database
?>