DekGenius.com
Previous Section  < Day Day Up >  Next Section

12.4 Fixing Database Errors

When your program involves talking to a database, you have to deal with an additional universe of errors. Just as the PHP interpreter expects your programs to adhere to a particular grammar, the database program expects your SQL statements to adhere to the grammar of SQL.

The setErrorHandling( ) function introduced in Section 7.4 has an additional mode of operation that gives you increased control over how database errors are handled in your PHP programs. Instead of having a terse error message printed or your program exit when a database error happens, you can have a custom function called. That function can do whatever you want, such as print a more detailed error message or write to the web server error log.

To enable this mode, call setErrorHandling( ) with the PEAR_ERROR_CALLBACK constant and the name of your error-handling function. Example 12-8 says that when there is a database error, the database_error( ) function should be called.

Example 12-8. Setting up a custom database error handling function
$db->setErrorHandling(PEAR_ERROR_CALLBACK,'database_error');

You also have to write the custom error-handling function whose name is passed to setErrorHandling( ). This function must accept one argument. When DB invokes the function, it passes an object to the function that contains the error information. You can use the getDebugInfo( ) method of that object to get more detailed error information. Example 12-9 is a sample custom error-handling function.

Example 12-9. A custom database error handling function
function database_error($error_object) {
    print "We're sorry, but there is a temporary problem with the database.";
    $detailed_error = $error_object->getDebugInfo( );
    error_log($detailed_error);
}

The database_error( ) function defined in Example 12-9 prints a generic message when a database error happens. It sends more detailed information about the error to the web server error log. Because this detailed information includes the full text of the database queries that caused errors, you shouldn't show it to your web site visitors. The messages that database_error( ) sends to the error log look like this:

SELECT dish_name, price, has_spiciness FROM dishes WHERE price >= '5.00' AND price <= 
'25.00' AND is_spicy = 0 [nativecode=1054 ** Unknown column 'has_spiciness' in 'field 
list']

Since the dishes table doesn't have a column called has_spiciness, a query that tries to use such a column fails.

    Previous Section  < Day Day Up >  Next Section