User Tools

Site Tools


pdo:exception_handling

PDO - Exception Handling

PDO has three error handling modes.

  • PDO::ERRMODE_SILENT acts like mysql_* where you must check each result and then look at $db→errorInfo(); to get the error details.
  • PDO::ERRMODE_WARNING throws PHP Warnings
  • PDO::ERRMODE_EXCEPTION throws PDOException. In my opinion this is the mode you should use. It acts very much like or die(mysql_error()); when it isn't caught, but unlike or die() the PDOException can be caught and handled gracefully if you choose to do so.
<?php
try {
  // Connect as appropriate as above.
  $db->query('hi'); // Invalid query!
} catch(PDOException $ex) {
  echo "An Error occured!"; // User friendly message.
  some_logging_function($ex->getMessage());
}

NOTE: You do not have to handle with try catch right away. You can catch it anytime that is appropriate. It may make more sense to catch it at a higher level like outside of the function that calls the PDO stuff:

<?php
function getData($db) {
  $stmt = $db->query("SELECT * FROM table");
  return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

…then much later…

try {
  getData($db);
} catch(PDOException $ex) {
  // Handle me.
}

or you may not want to handle the exception with try/catch at all, and have it work much like or die(); does. You can hide the dangerous error messages in production by turning display_errors off and just reading your error log.

pdo/exception_handling.txt · Last modified: 2020/07/15 10:30 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki