|
MySql Error Handling in PHP |
|
|
|
|
Thursday, 12 February 2009 |
The standard mysql library calls provide two methods for accessing error information, mysqk
Let's look at an example first:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
In this example we are attempting to connect to a mysql database. Like most of the mysql functions, [b]mysql_connect[/b] either returns a value (in this case a handle to the database) or returns false, meaning an error occurred.
You can access the error message number and text using the calls [b]mysql_errno()[/b] and [b]mysql_error[/b]. In both cases you can pass in a handle to specify which handle you want errors or if you do not pass in a handle the last database operation is used as a reference point.
Both functions also only work for the last database operation that occurred. So, if you want to retrieve error information you must retrieve it immediately after a mysql function call. Every mysql function call resets the error number and message text result.
Here are some examples of error number and text messages that might occur:
1049: Unknown database 'xyzzy'
1146: Table 'mytable' doesn't exist
Some of the common errors that occur are:
Access denied - the username/password combination you are using does not have the access you need to perform the mysql function requested.
Can't connect to [local] MySQL server - most likely you have incorrect information regarding the connection parameters
Lost connection to MySQL server - usually indicates network connectivity trouble and you should check the condition of your network if this error occurs frequently
Client does not support authentication protocol - happens frequently on a database that needs to be upgraded
Host 'host_name' is blocked - the mysql server has determined that too many connection attempts are occurring
Too many connections - means that all connections are busy. This is typically caused by programs that do no release connections when complete.
Out of memory - your query is going to use too much memory. You should review your query to make sure too many rows are not being retrieved at once.
Table 'tbl_name' doesn't exist - the table named does not exist, most likely a typo in your query |