如何使用数组作为列与mysql表的列连接?

时间:2012-08-15 22:32:34

标签: php arrays

我有一个post_ids数组

$ids = array( 
    [0] => 32 
    [1] => 33 
    [2] => 21 
    [3] => 11 
    [4] => 13 
    [5] => 17 
    [6] => 41 
    [7] => 88 
    [8] => 92 
    [9] => 94 
    [10] => 96 
    [11] => 106 
    [12] => 117 
    [13] => 187 
    [14] => 220 
);

我想在数据库表中获取一个列,其中post_id与上面数组中的id匹配。该表的结构如下

post_id | meta_key | meta_value

目前,我正在使用foreach ($ids as $id)逐个查询var。对于大型数据集,这是低效的。有没有办法通过$ ids数组查询meta_value列?

1 个答案:

答案 0 :(得分:0)

这不是最有效的方式,但它有效

$idList = implode(",",$ids);

现在是您的查询

$query = "SELECT * FROM posts 
          WHERE post_id IN ($idList);";

至少现在它被简化为一个查询

<强>更新

要在填充数组时保护SQL注入,请确保数据库输入是安全的:

// if you are populating your array this way here is the trick
$ids = array();
foreach ($inputValues as $value){
   $ids[] = (int) $value; // this makes sure your input is an integer
}