Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

php

I am trying to quickly determine if a user_ID is the owner of a 'goal'. I believe my SQL query is good, but I'm trying to find a nice way of checking the result!

In this case, no matter what I put for $obj_id or $user_id, my function returns true. I assume it's because mysql_num_rows is counting even a false result as a row? So what PHP code should I use to check to see if the result exists or not?

Note that I want something short and elegant! I know I could do it the long way (check count(*), return mysql_assoc then check the count value...) but that is long winded and ugly.

Any ideas? Thanks!

$query = "SELECT EXISTS (SELECT * FROM goals WHERE goal_ID='$obj_id' AND user_ID='$user_id')"; if (@mysql_num_rows(mysql_query($query))!=1) {     return false; } else {     return true; } 
like image 538
supermitch Avatar asked Dec 19 '10 20:12

supermitch


People also ask

How do you check if data exists in SQL?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

What does select exists return?

The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.

How do you check if a value exists in a database?

To check whether a particular value exists in the database, you simply have to run just a regular SELECT query, fetch a row and see whether anything has been fetched. Here we are selecting a row matching our criteria, then fetching it and then checking whether anything has been selected or not.


2 Answers

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 
like image 83
gbn Avatar answered Oct 14 '22 14:10

gbn


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; 
like image 32
Brad Mace Avatar answered Oct 14 '22 14:10

Brad Mace