I’ve been trying to improve the way we handle errors from a DB operation in PHP. We use ADODB for all our database access currently do stuff like:
$rs = $database->Execute($db)
or die($database->ErrorMsg() . "<br>" . $sql .
"<br>" . __FILE__ . " " . __LINE__)
Nothing wrong with this code, except that the die()
statement has to be everywhere and if we ever want to change it, then we have to change it everywhere!
Looking through the docs for ADODB I discovered that if you include “adodb-errorhandler.inc.php” then if will report the error and die gracefully for you. However, it doesn’t tell you the file line number where the error happened. Having the file and line number where the error was generate is really useful, so I decided to fix the ADODB version. This turned out to be quite easy – all you need to do is use PHP’s debug_backtrace()
to get the correct file and line number.
Having now implemented this, We can now write:
$rs = $database->Execute($db);
and know that if it fails, we’ll get a useful error message to debug from!