Page 1 of 1

More useful error reporting

Posted: Mon Mar 09, 2009 6:26 am
by JeffG
I haven't posted much in this forum, but I've seen a lot of posts that have "or die(mysql_error())" after a call to mysql_query or, worse, no error test at all, so I thought I'd share this.

mysql_error() on its own doesn't really tell you very much at all. I have written quite a large system with many files, most of them having several queries. All my queries are of the form:

Code: Select all

 
$rs = mysql_query($query) or db_error(__FILE__, __LINE__, $query, "any extra info");
 
The function db_error is in a file db_error.inc which I include in all my php files:

Code: Select all

 
<?php
// Copyright © 2008, J. R. Goodenough
function db_error($file, $line, $query, $extra)
{
    $_SESSION['error_file']   = basename($file);
    $_SESSION['error_line']   = $line;
    $_SESSION['error_extra']  = empty($extra) ? "(none)" : $extra;
    $_SESSION['error_number'] = mysql_errno();
    $_SESSION['error_desc']   = mysql_error();
    $_SESSION['error_query']  = $query;
    echo "<script type='text/javascript'>
        document.location.href='error.php?".SID."'</script>";
    exit();
}
?>
 
In my case, error.php displays a page with all the information, requesting the user tell the maintainer, and a button to return to the main menu page. Roll your own error.php to suit your own situation.

99 times out of 100 I have been able to see what's wrong immediately (such as missing substitutions in the query) and, most importantly, where it happened.

Hope this helps someone.

Re: More useful error reporting

Posted: Mon Mar 09, 2009 7:12 am
by susrisha
nice implementation. Its been a while since i wrote something that deals with mysql nowadays. But will surely use it when i get a chance.
PS: Have been working on Action Script and Flash lately ;)