开发者

PHP: MySQL error hook?

开发者 https://www.devze.com 2022-12-14 11:55 出处:网络
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 en

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 开发者_JAVA技巧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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消