I Have an array of different ids, I want to iterate this array and use these ids to be compared with a single field i开发者_JAVA技巧n 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?
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.
精彩评论