InsaneCoder
InsaneCoder

Reputation: 8268

Finding if an ID exists in a table using Mysql EXISTS an PHP

I have a table which keeps record of users who have given the test.Since I want the user to attempt test only once, first I check if he has given it before allowing him to take test.

Test_Attempted

-------------------------------
User_id    |  Name
-------------------------------

Now I am using the following query

select exists(select user_id from Test_Attempted where user_id=45) as present

But since id 45 is already present ,it returns

+---------+
| present |
+---------+
|       1 |
+---------+

Now I am confused how to use it in if-else (using PDO)

if(present)
   echo "You have given test";
else
   echo "Take test";

Do I need to cycle through rows using while loop,even if the returned row is single?

Upvotes: 0

Views: 164

Answers (1)

Barmar
Barmar

Reputation: 780994

No, you don't need a while loop if you know there's always exactly one row. It seems to me that this should be intuitively obvious, but hardly a day goes by that I don't see a question containing a while loop for a known single row.

$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row['present']) {
    echo "You have given test";
} else {
    echo "Take test";
}

Upvotes: 1

Related Questions