0

How do I use in_array() function in where condition in MYSQL?

It should check all key of Array

$arr=array(1,2,3,4,5);  
$query="select * from tablename where id='$arr'";
NFTtray
  • 75
  • 10
  • 1
    `in_array()` doesn't exist in `mysql`. You could iterate over the array and build a `where` clause. Example https://stackoverflow.com/questions/53400701/dynamically-creating-or-conditions-by-passing-an-array-to-a-query-in-mysql-php/53400798#53400798 – user3783243 Dec 15 '18 at 10:29

2 Answers2

1

MySQL uses the syntax WHERE id IN (1, 2, 3, 4, 5). You can use implode() to convert your array to that kind of string.

$arr = array(1, 2, 3, 4, 5);
$list = implode(",", $arr);
$query = "select * FROM tablename WHERE id IN ($list)";
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • actually i have to join two table with ON condi1=condi2 – NFTtray Dec 15 '18 at 09:13
  • 2
    That's a completely different question. – Barmar Dec 15 '18 at 09:15
  • If you're trying to match an element of a comma-seprated list stored in a column, see https://stackoverflow.com/questions/16208565/search-with-comma-separated-value-mysql/16210672#16210672 – Barmar Dec 15 '18 at 09:16
  • 1
    I can only answer the question you actually asked, not the question you meant to ask instead. – Barmar Dec 15 '18 at 09:17
1

You can make use of mysql 'IN' clause. Step 1 : implode your array by using PHP implode function. Step 2 : Pass that array to mysql query using IN clause.

Eg :

$array = array(1,2,3);
$implArray = implode(",",$array);
$query = "select * from `tablename` where `id` IN ($implArray)";

Above condition will work where array values are numeric.

For Alphanumeric Values, you will have to quote the values. eg :

$array = array('A','B','C');
$implArray = implode("','", $array);
$query = "select * from `tablename` where `id` IN ('"'.$implArray.'"')";
Barmar
  • 741,623
  • 53
  • 500
  • 612