Databases Reference
In-Depth Information
Handling errors using the older MySQL library
The default MySQL (as opposed to MySQLi) library has two similar error-handling
functions that you can use to check for problems. The function
mysql_errno( )
returns
an error number for the most recent MySQL function that used the specified connec-
tion; if no error occurred, it returns 0. Similarly, the function
mysql_error( )
returns a
string describing an error for the most recent MySQL function that used the specified
connection; if no error occurred, it returns the empty string
""
. Note that neither works
for the
mysql_connect( )
function; both need a working connection as a parameter to
interrogate the MySQL server about the error. The old MySQL function library doesn't
have any equivalents for the MySQLi functions
mysqli_connect_error( )
and
mysqli_connect_errno( )
, so you need to check for a failed connection yourself, perhaps
by calling the
die( )
function to print an error message and stop processing.
Let's look at an example. Suppose you have the following fragment that tries to use the
nonexistent
vapor
database:
// Connect to the MySQL server
if (!($connection = @ mysql_connect("localhost", "root",
"
the_mysql_root_password
")))
die("Cannot connect");
if (!(@ mysql_select_db("vapor", $connection)))
die(mysql_error($connection) . " (" . mysql_errno($connection) . ")");
The final line of the fragment concatenates a string that describes the error using
mysql_error( )
and then includes in parentheses the error number using
mysql_errno( )
. When you run the fragment, you get the output:
Unknown database 'vapor' (1049)
As with the MySQLi library, you could write a simple function to handle MySQL errors:
// Custom error handler function
function showerror($connection)
{
die(mysql_error($connection) . " (" . mysql_errno($connection) . ")");
}
You could then call this function instead of the
die( )
function and pass it the
$connection
parameter:
// Connect to the MySQL server
if (!($connection = @ mysql_connect("localhost", "root",
"
the_mysql_root_password
")))
die("Cannot connect");
if (!(@ mysql_select_db("vapor", $connection)))
showerror($connection);