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
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));
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. :)
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.
You need something like:
$sql = "SELECT * from table where comp_id in (".implode(',',$arr.")";
you can only pass string to mysql as query, so try this
mysql_query("SELECT * FROM table WHERE comp_id IN (".implode(',',$arr).")");
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')";