When using PDO (PHP Data Objects) in PHP, you can handle errors and exceptions in the following ways:
setAttribute()
method with the PDO::ATTR_ERRMODE
attribute set to PDO::ERRMODE_EXCEPTION
. For example:$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
PDOException
to handle exceptions gracefully. For example:try {
// Code that may raise PDO exceptions
} catch(PDOException $e) {
// Handle the exception (e.g., Log the error, display a friendly error message, etc.)
}
errorInfo()
method to determine if an error occurred. The errorInfo()
method returns an array containing error information (if any). For example:$stmt = $pdo->prepare("SELECT * FROM users");
if ($stmt->execute()) {
// Fetch the results
} else {
// Handle the error using $pdo->errorInfo() method
$errorInfo = $pdo->errorInfo();
// Log the error or display a friendly error message, etc.
}
It's recommended to use a combination of both setting the error mode and using try-catch blocks to handle errors and exceptions effectively.