How to handle errors and exceptions when using PDO in PHP?

When using PDO (PHP Data Objects) in PHP, you can handle errors and exceptions in the following ways:

  1. Set the error mode: Before executing any query, you can set the error mode to make PDO throw exceptions on errors. This can be accomplished by using the 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);
  1. Surround code with try-catch: Wrap the code that potentially raises PDO exceptions with a try-catch block. You can catch the 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.) }
  1. Use errorInfo method: After executing a query, you can check the 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.