0

I want to fetch some specific rows from MySQL database using multiple ids, for example if I have to select only rows 201,567,991 etc...

like this

$sql_query = "SELECT * from tbl_name WHERE id = '201', '567', 'id-etc.'";

is it possible in MySQL?

3 Answers 3

2

IN() should do the trick. Just put your list of numbers inside the brackets like so:

$sql_query = "SELECT * from tbl_name WHERE id IN(1, 2, 3, ...)";

You don't need to quote numbers going into INT fields, however it's a very good idea to cast any variables to int, to minimise security vulnerability:

$var = (int)$var;

If you're using strings, however, do quote them as you normally would.

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

2 Comments

@ImranHussain, I would suggest just using mysql_real_escape_string() for everything and just quoting all your numbers. That way all your escaping code looks the same and you cannot make mistakes. If you leave an escaped string unquoted you are wide open to SQL-injection. If you quote a number everything works OK, with exactly the same performance.
This doesn't fetch rows in exactly the order given.
1

Yes. Use IN Link

$sql_query = "SELECT * from tbl_name WHERE id IN ('201', '567')";

Comments

1

Use tge "IN" operator as in:|

 SELECT * from tbl_name WHERE id In ('201', '567', 'id-etc.')

Comments

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.