Fuxi
Fuxi

Reputation: 7599

php/mySQL: querying records by id from array?

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

Answers (3)

1000111
1000111

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 that OR evaluates them one by one in no particular order. So IN is faster in some circumstances.

Related post

Upvotes: 1

Simon
Simon

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

Nana Partykar
Nana Partykar

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

Related Questions