0

I'm using php and need to do a bunch of select statements on the same table and column and get the rows that match those values.

I have all the values I'm searching on in an array and right now I'm just looping and doing a select statement on each one separately. How could I put this all into one select statement and ditch the loop?

Right now it's like this:

for (yaddah yaddah yahhah){
    SELECT * FROM scan WHERE order=var[$i];
}
2
  • Nearly the same as stackoverflow.com/questions/2382831/… posted just 30 minutes before. Commented Mar 4, 2010 at 22:02
  • Yeah sorry. I looked but didn't see that one. Commented Mar 4, 2010 at 22:38

3 Answers 3

3

You could use IN to specify a list of values :

select * 
from scan
whenre order IN (1, 5, 46, 78)

And you can get such a list using the [`implode`][1] function :
$array = array(1, 5, 46, 78);
$list_str = implode(', ', $array);
// $list_str is now "1, 5, 46, 78"

$query = "select *
from scan
where order IN ($list_str)
";

After, in your PHP script, it's only a matter of fetching several lines instead of only one.

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

1 Comment

Thanks, this is much simpler than creating a temp table like I was told somewhere else.
1

Use IN and implode as follows:

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

Comments

0

Check out SQL's In Operator

Comments

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.