Reputation: 7599
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
Upvotes: 0
Views: 31
Reputation: 13519
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 thatOR
evaluates them one by one in no particular order. SoIN
is faster in some circumstances.
Upvotes: 1
Reputation: 3730
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
Upvotes: 0
Reputation: 10548
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)";
Upvotes: 0