error_exists() and error().
Whilst error_exists() checks for error, error() returns the error itself.
$db = ($dbc = new DB())->openDB();
if( $db ) {
echo 'Database connected successfully';
} else {
echo $dbc->error();
}
openDB() method returns a DBHandler class
else if not successful, it returns an empty value. If an empty value is returned, then an error must have occured. In order
to handle that error, we have to call the error() method from the class itself which returns the last occured error.
active() method while currentDB() returns the currently selected database name.
$db = ($dbc = new DB)->openDB();
if($dbc->active()) {
// output the current database selected
echo $dbc->currentDB();
} else if( $dbc->error() ) {
// some error occured
echo $dbc->error();
} else {
// No attempt to connect to database yet!
}
error() method. The beauty of this
approach is that no error gets printed if a connection has not been previously attempted. It is
however important to note that when a default connection e.g dbconfig.php is set, this is
assumed to be a previous connection.
error_exists() and error() methods just as discussed earlier
$db = ($dbc = new DB)->openDB();
if($db) {
// handler connected : run sql
$db->query('select * from users')->read();
if( $results = $db->results() ) {
var_dump( $results );
} else if ( $db->error_exists() ) {
echo $db->error();
}
} else {
// database connection failed
echo $dbc->error();
}
$db to run a query and tested for errors using
error_exists and error methods respectively. The error()
method can also be used to replace error_exists(). However, using error_exists
helps to make our code more readable.
DBStatus::error() which returns the last error encountered when a
database operation is performed. This is the global way to fetch an error and it returns any error encountered.
$db = ($dbc = new DB)->openDB();
if(DBStatus::error()) {
// output the error
echo DBStatus::error();
}
$db->error() does not return an error, if an error exists,
the DBStatus::error() may still be able to find it. However, to ensure that $db->error()
always an error if it exists, it has to be set to global mode. This is done by supplying an argument of true to the
$db->error() method which will ensure that it remembers to check the DBStatus::error() for any error too.
The DBStatus::error() may also be useful when working with database relationships.