MySQL 从表中选择多个 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20762424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 19:43:04  来源:igfitidea点击:

Select Multiple Ids from a table

mysqlsqlselectin-clausefind-in-set

提问by Irene T.

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.

我想根据 url 字符串选择一些 id,但我的代码只显示第一个。如果我写手册,id 就很好用。

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

我有这样的网址http://www.mydomain.com/myfile.php?theurl=1,2,3,4,5(ids)

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

现在在 myfile.php 我有我的 sql 连接和:

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

$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?

有什么建议?

回答by Jeremy Smyth

When you interpolate

当你插值时

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

with your IDs, you get:

使用您的 ID,您将获得:

"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.

...它将您的一组 ID 视为单个字符串而不是一组整数。

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

去掉IN子句中的单引号,像这样:

"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:

另外,不要忘记您需要检查SQL 注入攻击。您的代码目前非常危险,并且存在严重数据丢失或访问的风险。考虑如果有人使用以下 URL 调用您的网页并且您的代码允许他们在单个查询中执行多个语句,可能会发生什么情况:

http://www.example.com/myfile.php?theurl=1);delete from info;-- 

回答by Saharsh Shah

You can also try FIND_IN_SET()function

您也可以尝试FIND_IN_SET()函数

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

OR

或者

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