Handling MySQL Errors
When it comes to handling SQL querying problems, these are often easier to fix than pure PHP problems because you can narrow down the position of the error very easily, then analyze the faulty SQL line to spot the problem.
Always check that your code is actually correct. Use the MySQL monitor to try your queries out to make sure they do what you think they should do, as it will show you your results in an easy-to-read manner and will also give you meaningful error messages if you have slipped up along the way.
Also, remember that mysql_query()
will return false
if the query failed to execute, which means you can test its return value to see whether your SQL statement is faulty. You should be wary of trying to wrap mysql_query()
up inside another function call, because if it returns false
due to a bad query, the chances are the parent function will error out. For example:
extract(mysql_fetch_assoc(mysql_query("SELECT Blah FROM Blah WHERE Blah = $Blah;")));
Yes, it is perfectly valid SQL and under ideal conditions should work, but what if $Blah
is unset? Another possibility is that $Blah
might end up being a stringâthere are no quotes around $Blah
, which means that if $Blah
is a string, MySQL will consider it to be a field name, and the query will likely fail.
If the query does fail for some reason, mysql_fetch_assoc()
will fail and output errors, then extract()
will fail and output errors, causing a mass of error messages that hinder more than help. This code ...
Get PHP in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.