How to check if mysql_query returned something or not

Possible duplicate:
mysql_fetch_array () expects parameter 1 to be a resource, boolean is set to select

So, I'm trying to check if the next query returns any result or not

$numUsersSameRatingQuery="SELECT * `user ratings` WHERE category='$category' AND categoryId='$categoryId' AND `userAromaRating`>0 "; $result=mysql_query($numUsersSameRatingQuery); $numResults=mysql_num_rows($result); if($numResults==0) { // do the INSERT INTO } else { //do the UPDATE SET } 

However, the above returns the following error, and if($numResults) is executed anyway every time. In other words, I can never run the else block.

Here is the error

  Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\boozeDb\profileThis.php on line 141 

Helps to evaluate.

+4
source share
3 answers

You can use is_resource to make sure it is a resource. You can also use the if to ensure that FALSE not been returned.

To display this error, use mysql_error .

Example:

 <?php // From http://ca2.php.net/manual/en/function.mysql-query.php $result = mysql_query('SELECT * WHERE 1=1'); if (!$result) { trigger_error('Invalid query: ' . mysql_error()); } 
+8
source

mysql_query () either returns a handle to the instruction (the query is being executed) or a boolean value of FALSE (the query is not completed). Your code does not check for errors and blindly accepts success. Change the code to look like this:

 $result=mysql_query($numUsersSameRatingQuery) or trigger_error(mysql_error()); ^^^^^^^^^^^^^^^^^^^^^^--- add this 

Given your sample query, you are missing the FROM keyword and probably should be:

 SELECT * FROM `user ratings` ^^^^^^ 

I would STRONGLY urge NOT to use field names containing spaces. This is nothing but trouble.

+2
source

Like everyone else commented, an if or "or die ()" statement may help not to generate this error again, while the error probably comes from the missing "FROM" in your request.

I just felt the need to comment on the fact that now you are making TWO queries to prevent duplication of some or all of the columns in the table: SELECT and INSERT. This can be done in one question and speed up your code:

INSERT .. (what you want to insert) .. ON DUPLICATE KEY UPDATE .. (what to update if it already exists).

for more information here is the MySQLs man page about this.

0
source

All Articles