开发者

A function to capture all MySQL errors?

Does anyone have a PHP function that for example if a mysql_error() happens due to well a MySQL error it will not output it?

By not output it I mean rather it not show the error on live site as I will use it with another function I have that would work a treat if I had a MySQL error function.

I am just finding it so annoying as I do it like this currently:

$q = mysql_query("SELECT * FROM something");

// if error occurs
if(!$q) {
   echo 'Error' . mysql_error();
} else {
  // el开发者_Go百科se no errors so continue
}

On some of my webpages see I have several queries in a script and I would like to just be able to include the function at the bottom of all my PHP code and if a MySQL error occurs anywhere in my script for the function to catch the error instead of me doing multiples of the code I quoted above.

That way I can save myself a lot of unnecessary work and implement it with my email error function.


One way is to write your own function, say sql_query, which looks something like this:

function sql_query($sql) {
    $q = mysql_query($sql);
    // if error occurs
    if(!$q) {
       //your error handling code
    } else {
       return $q;
    }
}

You then use this function wherever you want to do a sql query.

A much better way is to use PDO and the exceptions etc in that.


The most robust solution is to probably use trigger_error(). This way you can tie into PHP's error handling system which is already prepared to deal with development and production environments.

$querySql = 'SELECT * FROM `foo`';
$queryResult = mysql_query($querySql);

if (!$queryResult) {
    trigger_error('Unable to execute query: ' . $querySql, E_USER_NOTICE);
}

Of course, the most convenience would be to make a decorating function for mysql_query() that automatically triggered the error. The DRY principle always applies.


Make or use a DB abstraction layer.

Use Exceptions and catch all of them. Then you have a "setting" to turn on or off the display of errors or better yet, log them to file.


I think i don't understand what you need.

If you want to 'hide' error from being print on the page, you just can use de '@' prefix:

$q = @mysql_query("SELECT * FROM something");

With the '@', errors are suppressed to the end-user.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜