Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

mysql - Select Multiple Ids from a table

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;-- 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...