17

If I have an array of say, some ID's of users. How could i do something like this:

$array = array(1,40,20,55,29,48);
$sql = "SELECT * FROM `myTable` WHERE `myField`='$array'";

Is there a simple way to do this, I thought about looping through array items and then building up one big "WHERE -- OR -- OR -- OR" statement but i thought that might be a bit slow for large arrays.

2 Answers 2

27

Use IN:

$sql = "SELECT * FROM `myTable` WHERE `myField` IN (1,40,20,55,29,48)";

you can use implode(",", $array) to get the list together from the array.

Sign up to request clarification or add additional context in comments.

Comments

11

You want to use IN:

WHERE `myfield` IN (1,40,20,55,29,48)

Use implode to construct the string:

$sql = "SELECT * FROM `myTable` WHERE `myField` IN (" . implode(',', $array) . ")";

2 Comments

So would i do "IN ($array)" ?
No, use implode to construct the string.

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.