Skip to content
Advertisement

mysql selecting multiple rows that match array of ids

First of all:

Is this correct way of selecting multiple rows? Or is there a better way? Because it is not really OR, but all of them… So it just doesn’t sound right.

Question number 2:

This is my query that selects users with pagination:

Sometimes I want to pass array of users to return to this query, like array(1,2,3,4,5).

Obviously simply adding WHERE $array doesn’t work. So how would I do that?

Sometimes I don’t want to pass this array of ids, so how do I switch between state when there is id list and when there is not? Do I simply create php if else on prepare statement? That seems obvious, but it is better to ask about best practices 🙂

Advertisement

Answer

To obtain multiple values from the where clause, there is no need to use OR. Use in, like in the query below:

This is the same as the first:

So if you have an array of user ids, you must implode it with the ',' glue characters.

Here’s a complete example with php:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement