How to use php array with sql IN operator?

后端 未结 13 1727
北恋
北恋 2020-11-29 06:23

I have and array with two values and I want to use it with sql IN operator in select query.

Here is the structure of my table

id comp_id
1   2
2   3
         


        
13条回答
  •  执笔经年
    2020-11-29 07:08

    There are some risks of SQL injection in a few of the previous answers. It might be fine if you are completely certain about $arr being sanitized (and will stay that way). But if you aren't completely sure, you might want to mitigate such risk using $stmt->bindValue. Here is one way of doing it:

    # PHP
    $in_list = array();
    for ($i = 0; $i < count($arr); $i++) {
        $key = 'in_param_' . i;
        $in_list[':' . $key] = array('id' => $arr[$i], 'param' => $key);
    }
    $keys = implode(', ', array_keys($in_list));
    
    // Your SQL ...
    $sql = "SELECT * FROM table where id IN ($keys)";
    
    
    foreach ($in_list as $item) {
        $stmt->bindValue($item['param'], $item['id'], PDO::PARAM_INT);
    }
    $stmt = $this->getConnection()->prepare($sql)->execute();
    

提交回复
热议问题