What best practices should be followed when handling errors in PDO database connections in PHP?
When handling errors in PDO database connections in PHP, it is important to enable error reporting, set PDO error mode to exceptions, and catch exceptions to handle errors gracefully. This ensures that any errors encountered during database operations are properly handled and do not expose sensitive information to users.
// Enable error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
try {
// Set PDO error mode to exceptions
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Perform database operations
// ...
} catch(PDOException $e) {
// Catch exceptions to handle errors gracefully
echo "Connection failed: " . $e->getMessage();
}