Section 22.6. Handling MySQL Errors


22.6. 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 stringthere 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 is much better:

     $result = mysql_query("SELECT Blah FROM Blah WHERE Blah = $Blah;");     if ($result) {             extract(mysql_fetch_assoc($result));     } 

That isn't to say that having all three functions on one line is incorrect. However, you should be very sure of any SQL statement you use in that manner, because any mistakes will be very visible to your users.

A helpful function for debugging MySQL queries is mysql_error( ), which returns any MySQL errors from the last function call. Each time you call a new MySQL function, the value mysql_error( ) is wiped, which means you need to call mysql_error( ) as soon as your suspect mysql_query( ) has been called; otherwise, it might be wiped over by subsequent queries from your connection.



PHP in a Nutshell
Ubuntu Unleashed
ISBN: 596100671
EAN: 2147483647
Year: 2003
Pages: 249

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net