OM The Eternity
OM The Eternity

Reputation: 16244

compare single field in mysql for multiple values

I Have an array of different ids, I want to iterate this array and use these ids to be compared with a single field in DB Table

Example

classid{
0=>1,
1=>2
}

and I have table as

id name
1   myname
2   ur name
3   everyonename

Now how can i retrieve the values for both id=1 and id = 2 in just a Select query?

Upvotes: 1

Views: 1905

Answers (1)

Jon
Jon

Reputation: 437904

The query you want is:

SELECT * FROM table WHERE id IN (1,2)

To create this from PHP, you would use something like

$classid = array(1, 2);
$sql = sprintf('SELECT * FROM table WHERE id IN (%s)',
               implode(',', $classid));

You should be ultra careful to prevent SQL injections if the values in $classid are coming from an external source! Normally this is achieved with prepared statements and bound parameters, but in this case (where you want to use IN) this is not possible AFAIK.

Therefore you should sanitize the values yourself, using something like

// This will convert all the values in the array to integers,
// which is more than enough to prevent SQL injections.
$classid = array_map('intval', $classid);

Read more about protecting yourself from SQL injection.

Upvotes: 3

Related Questions