Latest MySQL Errors With PHP

Pinpointing where an error in a program is occurring is not always easy. This can be even more of a problem when you write an SQL query that produces an error. Take the following select statement, which is clearly wrong.

ELECT * FROM table;

I tend to do this at least every now and then, and don't usually spot it until it's too late. So when I then run mysql_query() on this statement nothing happens. As far as I can tell form the code the table contains no data.

To get the error message that is produced from the SQL you can use the mysql_error() function to return the error message. The single optional parameter is the resource identifier for the MySQL connection, but if you leave this out then PHP will use the latest resource created.

echo mysql_error();

This will print the following line in your PHP output.

You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right 
syntax to use near 'ELECT * FROM table' at line 1

To more intelligently print off your error message you can use the following:

$error = mysql_error();
if (strlen($error) > 0) {
 echo $error;
};

This code will only print off the error message if it is present.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.