繁体   English   中英

比较mysql中的单个字段的多个值

[英]compare single field in mysql for multiple values

我有一个不同ID的数组,我想对该数组进行迭代并使用这些ID与数据库表中的单个字段进行比较

classid{
0=>1,
1=>2
}

我有桌子

id name
1   myname
2   ur name
3   everyonename

现在,如何仅通过Select查询检索id = 1和id = 2的值?

您想要的查询是:

SELECT * FROM table WHERE id IN (1,2)

要从PHP创建此代码,您可以使用类似

$classid = array(1, 2);
$sql = sprintf('SELECT * FROM table WHERE id IN (%s)',
               implode(',', $classid));

如果$classid中的值来自外部, 则应格外小心,以防止SQL注入 通常,这是通过准备好的语句和绑定参数来实现的,但是在这种情况下(要使用IN ),AFAIK是不可能的。

因此,您应该使用以下方法自己清理值:

// This will convert all the values in the array to integers,
// which is more than enough to prevent SQL injections.
$classid = array_map('intval', $classid);

阅读有关保护自己免受SQL注入的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM