1

Im trying to pass an array that I already found by a query into another query. For example:

$first_query = "SELECT id FROM from Table WHERE user = '{$_SESSION['id'}'";
$result = mysql_query($first_query,$connection);
$ids = mysql_fetch_array($result);

This is where it gets tricky for me. I want to pass $ids into the next query.

$id_implode = implode(", ", $ids)
$second_query = "SELECT * FROM Table2 WHERE id = '{$id_implode}';

The second query doesnt seem to be working. Any help is greatly appreciated!

0

4 Answers 4

5

your second query's syntax is wrong. Once evaluated it should read

select * from Table2 where id in (1,2,3)

ditch the curly braces and change the = to in. Don't use OR - that's a dumb way of ignoring good sql functionality

EDIT: Teneff's comment makes a very good point - why are you approaching the problem in this way? If there is a relationship between the tables they can be joined and all the data you want can be retrieved in a single query. If for some reason you can't / won't join the tables you could at least try a sub-query

select * from table2 where id in (select id from table where user = $_SESSION['id']);
Sign up to request clarification or add additional context in comments.

Comments

1

To use a where statement with multiple entries to match on, use in ().

$id_implode = "'".implode("', '", $ids)."'"
$second_query = "SELECT * FROM Table2 WHERE id in ({$id_implode});

Comments

1

I think you should use IN

$id_implode = implode(", ", $ids)
$second_query = "SELECT * FROM Table2 WHERE id IN '({$id_implode})';

This assumes that $ids is made of int of course, otherwise you have to enclose eache entry in quotes. that means

IN (6,7,8,9)//this doesn't need quotes

IN ('lemon', 'orange')//needs quotes

Comments

1

try to use the IN syntax:

$id_implode = implode("', '", $ids);
$second_query = "SELECT * FROM Table2 WHERE id in ('{$id_implode}');

1 Comment

where id in must be surrounded by paraenthesis (). dev.mysql.com/doc/refman/5.1/en/expressions.html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.