5

I had made three tables.

Table1=users.And the column names are userid (auto_increment) and username.
Table2=hobbies. column names are hobbyid (auto_increment) and hobbyname.
Table3=users_hobbies. column names are FK_userid and FK_hobbyid.

Now hobbyname has cricket,football,volleyball.
During sign-up user selects only cricket and football and I store it in $_SESSION['hobby_id'] associative array.

But in profile he/she wants to add some more hobbies.

So I want to display list of hobbies which are not equal to $_SESSION['hobby_id'].

This , ofcourse didn't work:

foreach($_SESSION['hobby_id'] as $k=>$v)
{

  $query="select hobbyid,hobbyname from hobbies where hobbyid!= $v";
}  
Output was football,volleyball and cricket,volleyball....but i wanted only volleyball

So i want that

$query="select hobbyid,hobbyname from hobbies where hobbyid!=(multiple values of session hobby id)";

What code will I have to enter to get desired result(only volleyball)?

0

1 Answer 1

2

remove foreachloop and use NOT IN comparision in MySQL:

$query="
    SELECT hobbyid,hobbyname
    FROM hobbies
    WHERE hobbyid NOT IN (" . implode(',', $_SESSION['hobby_id']) . ")
";
Sign up to request clarification or add additional context in comments.

2 Comments

worked like a charm!.. there was problem when the $_SESSION['hobby_id'] was empty but i solved it by using simple if(empty($_SESSION['hobby_id']))...... thanks
Sure you have to check if variable is not empty, I give you only the final query. But you have to ensure, that $_SESSION['hobby_id'] contains only numeric values (in fact of SQL injection)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.