More useful error reporting

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
JeffG
Forum Commoner
Posts: 35
Joined: Wed Jan 30, 2008 1:42 pm
Location: Newbury, UK

More useful error reporting

Post 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.
User avatar
susrisha
Forum Contributor
Posts: 439
Joined: Thu Aug 07, 2008 11:43 pm
Location: Hyderabad India

Re: More useful error reporting

Post 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 ;)
Post Reply