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

Php 比较mysql中单个字段的多个值,php,mysql,select,Php,Mysql,Select,我有一个不同ID的数组,我想迭代这个数组,并使用这些ID与DB表中的单个字段进行比较 范例 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); $s

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

范例

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));
// 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);
如果
$classid
中的值来自外部源,则应格外小心防止SQL注入!通常,这是通过准备语句和绑定参数实现的,但在这种情况下(您想在中使用
),这是不可能的

因此,您应该自己清理这些值,使用类似

$classid = array(1, 2);
$sql = sprintf('SELECT * FROM table WHERE id IN (%s)',
               implode(',', $classid));
// 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);

了解更多信息。

非常感谢您提供的所有详细信息@Jon