我有一个不同 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 注入(inject)!通常这是通过准备好的语句和绑定(bind)参数来实现的,但在这种情况下(你想使用 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 的信息.
关于php - 比较 mysql 中的单个字段的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7346213/