如何正确解析SQL查询的数组

时间:2013-01-26 11:02:36

标签: php mysql

当你需要做这样的事情时:

SELECT * FROM userinfo WHERE id in (18,2,6,4,5)

id数组来自另一个查询,如:

$ids = $conn->fetchAll('SELECT origin from action WHERE url = "'.$url.'" AND SUBSTRING(origin,1,3)<>"pct" GROUP BY origin');

如果我需要解析数组以便为查询ID提供正确的格式:

    $norm_ids = '(';
    foreach ($ids as $ids) {
        $norm_ids .= $ids['origin'] .',';
    }
    $norm_ids = substr_replace($norm_ids ,"",-1) .')';

输出的ID如:(id1,id2,id3,id.......),所以我只是:FROM userinfo WHERE id in ". $norm_ids;

但对我来说似乎很难看,有没有办法更好地做到这一点?

4 个答案:

答案 0 :(得分:3)

你可以这样做:

$idStr = rtrim(str_repeat('?,', count($ids), ',');
$query = 'SELECT * FROM userinfo WHERE id in (' . $idStr . ')';

然后使用prepare()

$conn = $db->prepare($query);
$conn->execute($ids);
$res = $conn->fetchAll(...);

答案 1 :(得分:1)

SELECT * FROM user_info WHERE id IN (SELECT origin from action ......) ....

答案 2 :(得分:1)

您是否需要将id分开,还是可以将它们合并为1个查询?

可能是这样的:

SELECT * FROM userinfo WHERE id in (SELECT origin from action WHERE url = "'.$url.'" AND SUBSTRING(origin,1,3)<>"pct" GROUP BY origin');  

这样你就让sql server完成了这项工作。

答案 3 :(得分:1)

当我遇到这种情况时,我会使用trim

$norm_ids_str = '';
foreach ($ids as $ids) {
    $norm_ids_str .= $ids['origin'] .',';
}
$norm_ids = '(' . trim($norm_ids_str, ',') . ')';