10.10. Logging Debugging Information and Errors
Problem
You want access to information to help you debug database problems. For example, when a query fails, you want to see what error message the database returns.
Solution
Use DB::isError( )
to
investigate the results of a single query:
$sth = $dbh->query("SELECT aroma FROM zodiac WHERE element LIKE 'fire'");
DB::isError($sth) and print 'Database Error: '.$sth->getMessage();Use DB::setErrorHandling( ) to automatically take
action on any database error:
$dbh->setErrorHandling(PEAR_ERROR_PRINT);
$sth = $dbh->query("SELECT aroma FROM zodiac WHERE element LIKE 'fire'");Discussion
When they encounter an error, most PEAR
DB methods return an DB_Error object. The
DB::isError( ) method returns
true if it’s passed a
DB_Error object, so you can use that to test the
results of individual queries. The
DB_Error
class
is a subclass of PEAR::Error, so you can use
methods such as getMessage( )
to display information about the
error. If you want to display everything in the error object, use
print_r( )
:
$sth = $dbh->query('SELECT aroma FROM zodiac WHERE element LIKE 'fire'");
if (DB::isError($sth)) {
print_r($sth);
}Since there is no aroma column in the
zodiac table, this prints:
db_error Object ( [error_message_prefix] => [mode] => 1 [level] => 1024 [code] => -19 [message] => DB Error: no such field [userinfo] => SELECT aroma FROM zodiac WHERE element LIKE 'fire' \ [nativecode=1054 ** Unknown column 'aroma' in 'field list'] [callback] ...