How can proper error handling be implemented when using PDO in PHP to avoid fatal errors?
Proper error handling can be implemented when using PDO in PHP by setting the PDO error mode to PDO::ERRMODE_EXCEPTION. This will throw exceptions when errors occur, allowing you to catch and handle them gracefully in your code.
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Your PDO query code here
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}