How to check if mysql_query returned anything or not [duplicate]
Possible Duplicate:
mysql_fetch_array() expects parameter 1 to be resource, boolean given in select
So I am trying to check if the following 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 the if($numResults)
is executed anyway each time. In other words, I can never get the else
block to run.
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
Help开发者_运维百科s are appreciated.
You could use is_resource
to make sure that it's a resource. You could alternatively use an if
statement to make sure that FALSE
wasn't returned.
To display the 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());
}
mysql_query() either returns a statement handle (query succeeded) or a boolean FALSE (query failed). Your code does not check for error conditions and blindly assumes success. Modify the code to look like this:
$result=mysql_query($numUsersSameRatingQuery) or trigger_error(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^--- add this
Given your sample query, you're missing the FROM
keyword, and should probably be:
SELECT * FROM `user ratings`
^^^^^^
I would STRONGLY urge you to NOT use fieldnames that contain spaces. They're nothing but trouble.
Just like everyone else has commented, an if statement or an "or die()" could help not generating that error again, while the error probably comes from the missing "FROM" in your query.
I just felt the need to comment the fact that you're now making TWO queries to prevent some or all columns in the table from being duplicates: a SELECT and an INSERT. This could be done in ONE query and would speed up your code:
INSERT ..(what you want to insert).. ON DUPLICATE KEY UPDATE ..(what to update if it already exists)..
for more info here's MySQLs manual page about it.
精彩评论