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'";
1

2 Answers 2

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)";
Sign up to request clarification or add additional context in comments.

4 Comments

actually i have to join two table with ON condi1=condi2
That's a completely different question.
If you're trying to match an element of a comma-seprated list stored in a column, see stackoverflow.com/questions/16208565/…
I can only answer the question you actually asked, not the question you meant to ask instead.
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.'"')";

2 Comments

In the string case you also need to escape special characters in the strings.
Too bad this isn't his actual question. See the comment he posted below my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.