Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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 is ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page