Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

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

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...