26

I want to select some id's based on url string but with my code it displays only the first. If i write manual the id's it works great.

I have a url like this http://www.mydomain.com/myfile.php?theurl=1,2,3,4,5 (ids)

Now in the myfile.php i have my sql connection and:

$ids = $_GET['theurl']; (and i am getting 1,2,3,4,5)

if i use this:

$sql = "select * from info WHERE `id` IN (1,2,3,4,5)";
$slqtwo = mysql_query($sql);
while ($tc = mysql_fetch_assoc($slqtwo)) {
    echo $tc['a_name'];
    echo " - ";
}

I am Getting the correct results. Now if i use the code bellow it's not working:

$sql = "select * from info WHERE `id` IN ('$ids')";
$slqtwo = mysql_query($sql);
while ($tc = mysql_fetch_assoc($slqtwo)) {
    echo $tc['a_name'];
    echo " - ";
}

Any suggestions?

Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
Irene T.
  • 1,393
  • 2
  • 20
  • 40
  • 1
    What is `$ids`? Note that because you've enclosed it in quotes, MySQL will treat it as a single item, so `'1, 2'` will return items with an ID of `1, 2`. – andrewsi Dec 24 '13 at 14:17
  • 2
    You may want to research SQL injection and PDO. Those will greatly improve your code. – Rayhan Muktader Dec 24 '13 at 14:20

2 Answers2

51

When you interpolate

"select * from info WHERE `id` IN ('$ids')"

with your IDs, you get:

"select * from info WHERE `id` IN ('1,2,3,4,5')"

...which treats your set of IDs as a single string instead of a set of integers.

Get rid of the single-quotes in the IN clause, like this:

"select * from info WHERE `id` IN ($ids)"

Also, don't forget that you need to check for SQL Injection attacks. Your code is currently very dangerous and at risk of serious data loss or access. Consider what might happen if someone calls your web page with the following URL and your code allowed them to execute multiple statements in a single query:

http://www.example.com/myfile.php?theurl=1);delete from info;-- 
Community
  • 1
  • 1
Jeremy Smyth
  • 23,270
  • 2
  • 52
  • 65
3

You can also try FIND_IN_SET() function

$SQL = "select * from info WHERE FIND_IN_SET(`id`, '$ids')"

OR

$SQL = "select * from info WHERE `id` IN ($ids)"
Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
  • This answer is unfortunately vulnerable to SQL injection – flaviut Jan 06 '23 at 20:25
  • @flaviut you are assuming the ids var isn't sanitized – user1689987 Jun 01 '23 at 15:41
  • doing this properly using `mysqli_prepare` is free, and does not depend on both writing the sanitation code correctly (*many* times it is wrong) and making sure no one accidentally forgets to sanitize data in future code (impossible). – flaviut Jun 02 '23 at 13:49