views:

62

answers:

2

I've been developing a web application with PHP and MySQL. The other day, I made some changes to the database and adapted one page to the new table layout but not another page. I didn't test well enough, so the site went online with the error still in the other page. It was a simple MySQL error, and once one of my co-workers spotted it, it was a simple fix.

Now that it's happened, I'd like to know how I can catch other MySQL errors. I'm thinking about some sort of notification system, that would send me an email when a mysql_query() fails.

I understand, of course, that I wouldn't be notified until after the error occurred, but at least I would have been notified immediately, rather than my co-worker come tell me after who-knows-how-many other people had run into the same fatal error.

Is there some sort of way to put in a hook, so that PHP automatically runs a function when an error happens? Or do I need to go through my code and add this functionality to every location where I use mysql_query()?

If the latter, do you have any recommendations on how to prevent something like this in the future? If this is the case I'll probably create a class to abstract SQL operations. I know I should have been doing this the whole time... But I did organize my sets of functions into different include files, so at least I'm doing most things right. Right?

+2  A: 

You can use custom functions for error handling using set_error_handler().

However, mysql_query won't trigger an error, but return false. The errors turn up only afterwards when trying to work with the results. In this case it might be better to define a custom wrapper function that calls mysql_query() and outputs possible errors using mysql_error(). That way, you can immediately halt your application on an error if so desired.

Pekka
In fact, instead of outputting the error, a good way to handle everything is to a) Have a single point of query execution b) Have a set_error_handler() set to handle the rest of the cases
Vinko Vrsalovic
+2  A: 

You could use a wrapper function like this:

function mysql_query_wrapper($query, $link=null)
{
    if (is_null($link)) {
        $result = myql_query($query);
    } else {
        $result = myql_query($query, $link);
    }
    if (mysql_error($result)) {
        // error occurred
    }
    return $result;
}

Then you just need to replace each mysql_query call with mysql_query_wrapper.

Gumbo
Thanks, and sorry @Pekka, I wish I could flag both of your answers as accepted. I think you've both given me the comprehensive answer and solution I was looking for!
Ricket