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
Since you have plain integers, you can simply join them with commas:
$sql = "SELECT * FROM table WHERE comp_id IN (" . implode(',', $arr) . ")";
If working with with strings, particularly untrusted input:
$sql = "SELECT * FROM table WHERE comp_id IN ('"
. implode("','", array_map('mysql_real_escape_string', $arr))
. "')";
Note this does not cope with values such as NULL
(will be saved as empty string), and will add quotes blindly around numeric values, which does not work if using strict mysql mode.
mysql_real_escape_string
is the function from the original mysql driver extension, if using a more recent driver like mysqli, use mysqli_real_escape_string
instead.
However, if you just want to work with untrusted numbers, you can use intval
or floatval
to sanitise the input:
$sql = "SELECT * FROM table WHERE comp_id IN (" . implode(",", array_map('intval', $arr)) . ")";
You need to implode your array with ',' comma
$imploded_arr = implode(',', $arr);
SELECT * from table Where comp_id IN ($imploded_arr)
As per @barryhunter 's answer which works only on array that contains integer only:
$sql = "SELECT * from table Where comp_id IN (".implode(',',$arr).")";
I've made some tweaks to make it work for array of strings:
$sql = "SELECT * from table Where comp_id IN ('".implode("','",$arr)."')";
You need to actually convert your $arr
to a string. The simplest way with what you're doing would be to use implode()
$query = 'SELECT * from table Where comp_id IN (' . implode(',', $arr) . ')';
Right now if you echo
your query you'll see that rather than the array being in the IN
statement, it will just be the word "Array"
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();
$arr is a php array, to the sql server you need to send a string that will be parsed you need to turn your array in a list like 1, 2, etc..
to do this you can use the function http://php.net/implode
so before running the query try
$arr = implode ( ', ', $arr);