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