Membership
Main Menu
Forum Boards
Stats
- 18 tutorials
- 72,305 members
- 696,115 forum posts
- 11 blog posts
Tutorials
Debugging: A Beginner's guide
Views: 26007
Database Errors
How often have you seen this?
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in C:\wamp\www\phpfreaks.php on line 5
The error message doesn't tell you a lot, does it? What it does tell you is that there was an error with your query. What we need is way of seeing that error. Handily, mysql_error() does just that. Now, you will see a lot of people on the forum (myself included) suggesting that to test a query you should add an or die statement and echo mysql_error() like so:
However, better practice would be to use "or trigger_error()". Why? Well, because it will save you troubles should the script go live. By throwing an error, you still get the benefit of seeing the problem whilst you are developing and have display_errors turned on, but can also handle things gracefully should the script go live and you turn of error_reporting. You'll also want to echo your query. It's so much easier to spot a syntax error when you actually look at what is being executed. This is particularly true if the query is complex and contains many variables.
Therefore, you should do this:
Notice that we create our query in a string before we execute it; this allows us to echo it.
Now, you might also have a query which does not generate an error, but also doesn't return what you expect. You may, for example, be expecting lots of rows but don't get any. Again, the best thing you can do is to echo the query:
9 times out of 10 you will find that a variable in your query doesn't contain what you expected it to and so can trace the error.
Finally, we'll talk a little bit about logical errors on the next page.
