How can error handling be improved in PHP when using PDO?
When using PDO in PHP, error handling can be improved by setting the error mode to PDO::ERRMODE_EXCEPTION. This will cause PDO to throw exceptions when errors occur, allowing for easier and more consistent error handling throughout your code.
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}