1

I have a session that contains an array and that array is filled with id's. What is the best way to select all the rows from a MySQL table that correspond to these id's?

So I need something like:

SELECT * FROM table WHERE id = $_SESSION['ids']

Obviously, this doesn't work, since $_SESSION['ids'] is an array.

3
  • You will have to use the IN() MySQL syntax and loop through your IDs into the IN() Commented Oct 8, 2013 at 11:58
  • duplicate: stackoverflow.com/questions/9476146/… Commented Oct 8, 2013 at 11:59
  • for using IN with an array, you first need to break the string. for find_in_set it would not be necessary Commented Oct 8, 2013 at 12:01

3 Answers 3

3
     SELECT * 
     FROM 
        table
     WHERE 
         find_in_set(id, $_SESSION['ids'])>0
Sign up to request clarification or add additional context in comments.

2 Comments

I tried the following to test your method: $_SESSION['ids'] = array(1,2,3); $db->query('SELECT * FROM table WHERE find_in_set(id, $_SESSION['ids'])>0'); It produces an error that I can't fix: Unknown column 'Array' in 'where clause'
print $_SESSION['ids'] ; find in set needs it in the form of a quoted string such as "1,2,3,4,5". Make sure you are echoing it in the right format.
2

You can just use IN SQL operator. In this case your query will look like

$sql = 'SELECT * FROM table WHERE id IN ("' . implode('","', $_SESSION['ids'] . '")';

This code will produse a query like following:

SELECT * FROM table WHERE id IN ("1", "2", "foo");

Hope it helps

Comments

1

HI Try This,

 $var = $_SESSION['ids'];

 and then fire your query as

 $sql = SELECT * FROM table WHERE id = '$var';

Comments

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.