Latest Post

Error: No input file specified.

While trying to run a codeigniter app the other day I came across this error just after I had finished uploading the files and making the ne...

Wednesday, April 8, 2009

mysql 'not a valid result resource' errors

Here's what's going on with 'not a valid result resource' errors. Take the following example:

PHP Code:
 $query 'SELECT * from table';
$result mysql_query($query);
$row mysql_fetch_array($result))
   { echo 
$row['foo']; }  
In the above, the mysql_query() function is sending the specific query to the database and returning a 'resource identifier', which is being set as the value of $result. These are not the results themselves -- if you echo $result at this point, you'll get 'Resource id #x'. The mysql_fetch_array() function in your while loop takes this resource identifier and creates an array of the actual db contents that you can use.

If your mysql_query() function fails to get a resource id, it returns a boolean FALSE instead. FALSE, of course, isn't a resource identifier, so when you try to pass it to mysql_fetch_array(), it will cough up the 'not a valid result resource' error. So all of you are getting failures in your mysql_query() function.

Using 'or die(mysql_error())' at the end of your mysql_query() call, will, instead of setting $result to FALSE, kill the script and, more importantly, return a more descriptive error message. 

Probably 80%+ of the time, a failed mysql_query() is caused by a syntax error in the query itself. Be especially mindful of any variables you're using in your query -- if they're not being set correctly, they can cause a syntax error. A failure to connect to the database can also cause mysql_query() to fail, so keep that in mind. Either way, the mysql_error() function will give you more information.

No comments:

Post a Comment

Chitika Ads