将mysql中的单个字段与多个值进行比较

时间:2011-09-08 09:57:50

标签: php mysql select

我有一系列不同的id,我想迭代这个数组并使用这些id与DB Table中的单个字段进行比较

实施例

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

我有桌子

id name
1   myname
2   ur name
3   everyonename

现在我如何才能在Select查询中检索id = 1和id = 2的值?

1 个答案:

答案 0 :(得分:3)

您想要的查询是:

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

详细了解protecting yourself from SQL injection