O'Reilly logo

Managing & Using MySQL, 2nd Edition by Hugh E. Williams, Randy Yarger, George Reese, Tim King

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required