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; }
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With