tags:

views:

319

answers:

3

Hi all,

I have a string:

 $string = "12,15,22";

Each of these values represents a usrID and I'd like to use these to select the rows associated with the $string.

Something like this:

SELECT usrFirst, usrLast FROM tblusers WHERE usrID = 12 OR 15 OR 22.

Now, the $string changes all the time, and sometimes can be a different number of ID's. Eg., sometimes 3, sometimes 4.

Thanks!

+3  A: 

use IN, although it is very slow if you have lots of numbers:

SELECT usrFirst, usrLast FROM tblusers WHERE usrID IN ($string)

W3Schools has more info on IN.

If you have lots of numbers, have a look here for info on how to speed this up.

Marius
Thanks for the help!
Dodinas
Don't forget to sanitize the values if they are coming from any form of user input.
Brenton Alker
+1  A: 

you can do something like:

SELECT usrFirst, usrLast FROM tblusers WHERE usrID in (12, 15, 22);

John Boker
+1  A: 

you can also do:

$string = str_replace(',',' OR usrID=',$string);
mysql_query('SELECT usrFirst, usrLast FROM tblusers WHERE usrID='.$string);
Shadow
-1 That ends up being SELECT usrFirst, usrLast FROM tblusers WHERE 12 OR usrID = 15 OR usrID = 22;
rezzif
So add usrID= before it. It was a simple, easily correctable error on my part.
Shadow
yeah you're right. sorry for being so harsh!
rezzif