0

i want to query several records by id like:

$ids = array(10,12,14,16,....);

the query would be something like:

select * from users where id=10 or id=12 or id=14 or id=16 ..

is it possible to query it in a more comfortable way like (compared to php):

select * from user where in_array(id, array(10,12,14,16))

thanks

Fuxi
  • 7,501
  • 24
  • 90
  • 138

3 Answers3

1

You can use IN instead of OR clauses

select * from users where id IN (put_your_array_here)

Example:

select * from users where id IN (10,12,14,16);

Note:

According to the manual for MySQL if the values are constant IN sorts the list and then uses a binary search. I would imagine that OR evaluates them one by one in no particular order. So IN is faster in some circumstances.

Related post

Community
  • 1
  • 1
1000111
  • 12,709
  • 2
  • 24
  • 33
0

Try this.

$id = array(10,12,14,16,....);

$ids = join("','",$id);
$sql =  "select * from user where id IN ('$ids')";

OR

$ids = implode(',', $id);
$sql =  "select * from user where id IN ($ids)";
Nana Partykar
  • 10,338
  • 9
  • 45
  • 76
0

You can do it like that using implode in PHP:

"select * from users where id in '".implode("','", $ids)."'"

Please be sure that your ids are safe though

Community
  • 1
  • 1
Simon
  • 3,200
  • 2
  • 19
  • 21