Skip to content
PHP Logo

How can PDO error handling be optimized to receive exceptions and improve troubleshooting in PHP?

To optimize PDO error handling in PHP, you can set PDO to throw exceptions for errors instead of just returning false. This allows you to catch and handle exceptions, making troubleshooting easier. To do this, simply set the PDO error mode to PDO::ERRMODE_EXCEPTION.

php
try {
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}