How to use php array with sql IN operator?

这一生的挚爱 提交于 2019-11-26 09:41:10

问题


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
3   1

I have an array $arr which have two values Array ( [0] => 1 [1] => 2 )

I want to fetch the record of comp_id 1 and comp_id 2. So I wrote the following query.

SELECT * from table Where comp_id IN ($arr)

But it does not return the results.


回答1:


As you have plain integers can just do...

$sql = "SELECT * FROM table WHERE comp_id IN (".implode(',',$arr).")";

(as it keeps coming up, some additional information... )

If working with with strings (particularly untrusted) input, can do

$sql = "SELECT * FROM table WHERE comp_id IN 
        ('".implode("','",array_map('mysql_real_escape_string', $arr))."')";

but does not cope values like NULL. And will add quotes blindly around numeric values, which does not work if using strict mysql mode. https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#idm140082377917056 ... ie ONLY use this if really working with strings (like VARCHAR), NOT numeric columns.

The Need to call something like mysql_real_escape_string is so that any quotes in the strings is properly dealt with! (as well as preventing SQL Injections!)


... if DO want to work with 'untrusted' numbers, can use intval or floatval

$sql = "SELECT * FROM table WHERE comp_id IN (".implode(",",array_map('intval', $arr)).")";

to sanitise the input. (no quotes around the input.




回答2:


you need to convert the array into comma-separated string:

$condition = implode(', ', $arr);

And, additionally, you might want to escape the values first (if you are unsure about the input):

$condition = implode(', ', array_map('mysql_real_escape_string', $arr));



回答3:


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



回答4:


You need to implode your array with ',' comma

$imploded_arr = implode(',', $arr);

SELECT * from table Where comp_id IN ($imploded_arr)



回答5:


you can only pass string to mysql as query, so try this

mysql_query("SELECT * FROM table WHERE comp_id IN (".implode(',',$arr).")");



回答6:


You're mixing PHP and SQL - for the IN SQL operator, you need a format like:

SELECT * from table WHERE comp_id IN (1,2)

So to get that in PHP you need to do something like:

$sql = "SELECT * from table Where comp_id IN (".implode(',',$arr).")"

Bear in mind that this only works if the array comprises of integers. You have to escape each element if they are strings.




回答7:


You need something like:

$sql = "SELECT * from table where comp_id in (".implode(',',$arr.")";



回答8:


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"




回答9:


You need to convert the array to a string for use in the query:

$list = implode(',', $arr);

Then it can be used in the IN clause:

SELECT * from table Where comp_id IN ($list)



回答10:


All the people here are proposing the same thing but i got a warning in WordPress because of a simple error. You need to add commas to your imploded string. To be precise something like this.

$query = "SELECT *FROM table Where comp_id IN ( '" . implode( "', '", $sanitized_brands ) . "' )";

Hoping it helps someone like me. :)




回答11:


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)."')";



回答12:


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



回答13:


If your array is of Integers :

$searchStringVar = implode(",",$nameIntAryVar);
$query="SELECT * from table NameTbl WHERE idCol='$idVar' AND comp_id IN ($searchStringVar)";

If your array is of Strings :

$searchStringVar = implode("','",$nameStringAryVar);
$query="SELECT * from table NameTbl WHERE idCol='$idVar' AND comp_id IN ('$searchStringVar')";


来源:https://stackoverflow.com/questions/9618277/how-to-use-php-array-with-sql-in-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!