How to check whether SELECT EXISTS returns a value or not?

Don't bother with EXISTS. The in-line exists will always give one row containing "true" or "false".

You're looking for either "zero rows" or "at least one row" so change the query to something like this and then check how many rows are returned

SELECT 1 FROM goals WHERE goal_ID='$obj_id' AND user_ID='$user_id' LIMIT 1

I like gbn's answer the best, but I wanted to point out that this:

if (@mysql_num_rows(mysql_query($query))!=1) {
     return false;
} else {
     return true;
}

can be simplified to:

return @mysql_num_rows(mysql_query($query)) == 1;

This way is probably faster.

$query = "SELECT EXISTS (SELECT * FROM goals WHERE goal_ID='$obj_id' AND user_ID='$user_id')";

if(mysql_num_rows(mysqli_query($query)) < 1) {
   // Nothing found!
}

Tags:

Sql

Php