0

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 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget to sanitize the values if they are coming from any form of user input.
1

you can do something like:

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

Comments

1

you can also do:

$string = str_replace(',',' OR usrID=',$string);
mysql_query('SELECT usrFirst, usrLast FROM tblusers WHERE usrID='.$string);

2 Comments

-1 That ends up being SELECT usrFirst, usrLast FROM tblusers WHERE 12 OR usrID = 15 OR usrID = 22;
So add usrID= before it. It was a simple, easily correctable error on my part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.