Handling MySQL Errors
The script in Example 11-2 includes MySQL error handling. Errors can occur in many different cases. For example, the MySQL DBMS might be unavailable, it might not be possible to establish a connection because the DBMS user’s credentials are incorrect, or an SQL query might be incorrectly formed.
Consider a fragment from Example 11-2:
// Run the query if (!($result = @ mysql_query ($query, $connection))) showerror( );
If the mysql_query( )
function returns false, the function
showerror(
)
is
called to output details of the error:
// Show an error and stop the script
function showerror( )
{
if (mysql_error( ))
die("Error " . mysql_errno() . " : " . mysql_error( ));
else
die("Could not connect to the DBMS");
}If a MySQL error has occurred, the script outputs the error number
and a descriptive string, and the PHP engine stops. If the error
isn’t a MySQL error, there is a problem connecting
to the DBMS with mysql_pconnect( ). The
showerror( ) function is part of the
db.inc include file.
When a function such as showerror( ) is used,
MySQL function calls are usually prefixed with the
@ operator.
The @ stops the PHP engine from outputting its own
internal error messages. If the @ is omitted, the
output of showerror( ) is shown interleaved with
the PHP engine’s internal error messages, which can
be confusing to debug.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access