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.

joepd
  • 49
  • 1
  • 8

3 Answers3

3
     SELECT * 
     FROM 
        table
     WHERE 
         find_in_set(id, $_SESSION['ids'])>0
plain jane
  • 1,009
  • 1
  • 8
  • 19
AdrianBR
  • 2,762
  • 1
  • 15
  • 29
  • 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' – joepd Oct 09 '13 at 09:35
  • 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. – AdrianBR Oct 09 '13 at 10:09
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

Spell
  • 8,188
  • 2
  • 16
  • 19
1

HI Try This,

 $var = $_SESSION['ids'];

 and then fire your query as

 $sql = SELECT * FROM table WHERE id = '$var';
rohitr
  • 371
  • 2
  • 11