MySQL Error Handler For PHP

Anyone that works with MySQL and PHP knows that it’s a good idea to trap and handle errors as a part of making calls to the database. I have seen folk that do it in many different ways, and some that don’t do it at all. It’s a real handy thing to do, especially in the early phases of development. If there is a problem somewhere in your code, good feedback from the application can make troubleshooting much easier. I tend to write functions that make life easier, put them all into a file and then reference that from my pages that actually do the work. In this case, I have a function that will catch and return MySQL errors, along with the query so you can see what is going wrong. First I will show you the function, and then I will show you some usage examples.

Here is the function itself:

function sqlerr($q) {
  $msg = "An error has occurred with the database query\n";
  $msg .= "

The query was: $q

\nThe error returned was: ".mysql_error(); die($msg); }

It should be pretty self explanatory, it’s a nice simple function just like I like ’em. Now, how would you use this? Well, it’s simple really. Check it out:

  $query = "select name,number from phonebook";
  $result = mysql_query($query) or sqlerr($query);

Simple, huh? You create the query and then when you execute it using mysql_query, if there are any errors, the app stops and displays the MySQL error message and the query so you can see if something went wrong. I find this very useful and I hope you do to.

Tell me what you are thinking?