Accessing Databases with ADODB - Understanding Error Handling
(Page 5 of 12 )
There are four ways to handle errors in ADODB. The first is to check the return value from each ADODB function call and explicitly take an appropriate action if there is an error. If you turn on the $conn->debug flag, you can see the error messages:
$conn->debug = 1;
$rs = $conn->execute('SELECT flavor,calories,price FROM cookies');
if (! $rs) { print "Query Error"; }
Because the cookies table doesn’t exist, an error message is printed that includes this text:
1146: Table 'phpgems.cookies' doesn't exist
Turning on $conn->debug also causes some diagnostic information about queries to be displayed, so this is not something you should do in a production environment. It is helpful for testing and debugging, however.
The second way is to use ADODB’s trigger_error() error-handling mode. In this mode, ADODB throws an error with PHP’s trigger_error() function whenever Connect(), PConnect(), or a query execution function such as Execute() fails. You don’t have to do anything special to check return values because your program exits when there is an error. To turn on this error handling mode, require the file adodb/adodb-errorhandler.inc.php. For example:
require 'adodb/adodb-errorhandler.inc.php';
// ... establish connection to the database ...
$rs = $conn->execute('SELECT flavor,calories,price FROM cookies');
This exits with the following error message:
Fatal error: mysql error: [1146: Table 'phpgems.cookies' doesn't exist] in EXECUTE("SELECT flavor,calories,price FROM cookies") in /usr/local/php/lib/adodb/adodb-errorhandler.inc.php on line 75
Because ADODB uses trigger_error() to throw these errors, you can catch them by defining your own error handler. Call set_error_handler() with the name of your error-handling function. The error-handling function can do whatever you want with the error. This example just prints the error message to the error log:
set_error_handler('check_errors');
$rs = $conn->execute('SELECT flavor,calories,price FROM cookies');
function check_errors($errno, $error, $file, $line) {
error_log("ADODB Error: $error");
}
The check_errors() function writes the following message to the error log:
ADODB Error: mysql error: [1146: Table 'phpgems.cookies' doesn't exist] in EXECUTE("SELECT flavor,calories,price FROM cookies")
One benefit of defining your own error handler is that your program doesn’t automatically exit when ADODB throws an error. If you want it to exit, you can call exit() or die() inside your error handler, but you don’t have to do so.
The third error handling method is to use ADODB’s PEAR_Error error-handling mode. Turn on this mode by requiring the file adodb/adodb-errorpear.inc.php. In this mode, ADODB creates a PEAR_Error object when Connect(), PConnect(), or a query execution function fails. You can use the PEAR_Error objects in two ways. First, by testing the return values from the ADODB functions and using the ADODB PEAR_Error() function, you can retrieve the error object when necessary and process it:
require 'adodb/adodb-errorpear.inc.php';
// ... establish a connection to the database ...
$rs = $conn->execute('SELECT flavor,calories,price FROM cookies');
if (! $rs) {
$err = ADODB_PEAR_Error();
error_log('Query Error: '.$err->getMessage());
}
Just like you can take action automatically on errors generated by trigger_error() if you set your own error handler, you can take action automatically when PEAR errors occur by using the PEAR::setErrorHandling() method. Call PEAR::setErrorHandling() with a constant that indicates how you want errors to be handled. The PEAR ERROR_PRINT constant causes the errors to be printed. The PEAR_ERROR_DIE constant causes errors to be printed, and then the program immediately exits:
PEAR::setErrorHandling(PEAR_ERROR_DIE);
$rs = $conn->execute('SELECT flavor,calories,price FROM cookies');
PEAR_Error mode also supports custom error handlers. Indicate the custom error handler to be called with the PEAR_ERROR_CALLBACK constant:
PEAR::setErrorHandling(PEAR_ERROR_CALLBACK,'check_errors'); $rs = $conn->execute('SELECT flavor,calories,price FROM cookies');
function check_errors($err) {
error_log('Query Error: '.$err->getMessage());
}
When an error occurs, the callback set up by PEAR::setErrorHandling() is called with a PEAR_Error object as its only argument. Inside the callback, you can print error messages, e-mail your database administrator there has been a problem, exit the program, or take any other action that the error warrants.
The fourth error handling method is with exceptions. This is only available if you are using PHP 5. Turn on this mode by requiring the file adodb/adodb-exceptions.inc.php. In this mode, ADODB throws an exception of type ADODB_Exception when an error occurs. Put your code that uses ADODB functions inside a try/catch block to handle an error:
require 'adodb/adodb-exceptions.inc.php';
try {
$conn = &ADONewConnection('mysql');
$conn->Connect('localhost','phpgems','phpgems1','phpgems');
$rs = $conn->execute('SELECT flavor,calories,price FROM cookies');
} catch (ADODB_Exception $e) {
print 'Database Error: '.$e->getMessage();
} catch (Exception $e) {
print "Something else went wrong: ".$e->getMessage();
}
The first catch block in the previous code handles any exceptions generated by ADODB, and the second catch block handles any other exceptions that may have been generated. In a database context, exceptions are useful for cleaning up any unfinished business. When handling an ADODB_Exception,you can roll back a partially completed transaction or close any open connections to a database.
Introducing Sequences ADODB provides integer sequences for you to use. You can retrieve the next value from a particular sequence by passing the sequence name to the genID() method:
$flavor_id = $conn->genID('flavors');
$conn->Execute('INSERT INTO ice_cream (id,flavor) VALUES (?,?)', array($flavor_id,'Walnut'));
If you call genID() without a sequence name, it retrieves the next value from the default sequence, named adodbseq. The genID() method creates a sequence if it doesn’t already exist. You can create a sequence without getting a new value from it with CreateSequence():
$conn->CreateSequence('flavors');
Whether created automatically by genID() or explicitly by CreateSequence(), sequences start at 1 by default. You can start a sequence by passing a second argument to genID() or CreateSequence():
$flavor_id = $conn->genID('flavors',31);
$conn->CreateSequence('flavors',31);
The genID() method only uses the second argument to set the start value of the sequence if it is creating the sequence. If the sequence already exists, genID() returns the next value in the sequence.
To delete an existing sequence, use DropSequence():
$conn->DropSequence('flavors');
This is from Essential PHP Tools, by David Sklar (Apress, ISBN 1590592808). Check it out at your favorite bookstore today. Buy this book now. |
Next: Generating HTML >>
More Database Articles
More By Apress Publishing