Databases Reference
In-Depth Information
For example, if an attempt to connect to the MySQL server fails, the
mysqli_connect( )
function returns
FALSE
and displays an error message, as below:
Warning: mysqli_connect() [function.mysqli-connect.html]: (28000/1045):
Access denied for user 'fred'@'localhost' (using password: YES)
in /var/www/html/wedding/index.php on line 68
MySQL data
These are error conditions that are detected programmatically, but are neither PHP
nor MySQL problems. For example, deleting rows that don't exist, returning in-
correct numbers of rows, and concurrency-related problems fall into this class.
Typically, these are design problems that are common to any database system.
You can use PHP to handle MySQL errors by testing for a
FALSE
return value from calls
to functions such as
mysqli_connect( )
and
mysqli_query( )
:
if(!($connection=@mysqli_connect
($DB_hostname, $DB_username, $DB_password, $DB_databasename)))
die("Failed while trying to connect to the database.");
Here, we've used the PHP
die( )
function to display an error message and stop the
program if
mysqli_connect( )
returns
FALSE
. It's common to suppress the default PHP
error messages by adding the at symbol (
@
) just before the call to MySQL functions;
without it, you'll get both a message from PHP's own error handler, which is cryptic
to a user, and your message from the
die( )
function. Here's another example:
// Run the query on the connection
if (!($result = @ mysqli_query($connection, "SELECT * FROM artist")))
die("Couldn't run query");
Handling errors using the MySQLi library
PHP provides error-reporting functions that provide the text error message and the
numeric error code for a MySQL error that has occurred. Error numbers make it easier
to look up information in the MySQL manual list of error codes and messages at
http:
The functions
mysqli_connect_error( )
and
mysqli_connect_errno( )
provide the error
message and numeric code corresponding to the latest error that occurred while
trying to initialize a given MySQL connection. If no error has occurred,
mysqli_connect_error( )
returns an empty string (
""
), and
mysqli_connect_errno( )
returns 0.
Similarly, the PHP functions
mysqli_error( )
and
mysqli_errno( )
provide the error
message and numeric code corresponding to the latest error on an active connection.
They do not report connection errors; the previous two functions do that instead.
Together, these can be used to report errors to the programmer, or to trigger code that
displays useful messages to the user. You could use these error-handling functions in
your own custom function; for example, you could display the error number and the
error message: