开发者

Use an array inside a query string

开发者 https://www.devze.com 2023-03-12 08:29 出处:网络
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\'}\'\";

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!


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']);


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});


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


try to use the IN syntax:

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

精彩评论

暂无评论...
验证码 换一张
取 消