我在WHERE子句中使用数组进行SQL查询时遇到问题。
例如:
我的阵列:
$myarray[1] = "hi";
$myarray[2] = "there";
$myarray[3] = "everybody";
我的MySQL声明:
SELECT * FROM myTable WHERE title='".$myarray[]."'
有没有办法实现这一点? 我自己解决了这个问题:
for(...) {
$where = $where." title='".$myarray[$count]."' OR ";
}
$where = substr($where , 0, -3);
.....
SELECT * FROM myTable WHERE ".$where."
但如果我的数组中有数千个条目,那么SQL语句会变得太大而且很慢,对吧?
由于
答案 0 :(得分:14)
您可以使用mysql的IN-function
编辑:正如amosrevira所说,你需要在数组中逃脱你的字符串。
$myarray[1] = "'hi'";
$myarray[2] = "'there'";
$myarray[3] = "'everybody'";
$newarray = implode(", ", $myarray); //makes format 'hi', 'there', 'everybody'
SELECT * FROM myTable WHERE title IN ($newarray);
答案 1 :(得分:8)
$myarray[1] = "hi";
$myarray[2] = "there";
$myarray[3] = "everybody";
//every quoted string should be escaped according to SQL rules
foreach($myarray as $key => $val) {
$myarray[$key] = mysql_real_escape_string($val);
}
$in_str = "'".implode("', '", $myarray)."'"; //makes format 'hi', 'there', 'everybody'
SELECT * FROM myTable WHERE title IN ($in_str);
答案 2 :(得分:3)
您可以使用IN
运营商。你希望它看起来像:
title IN ('hi', 'there', 'everybody')
所以你会做类似的事情:
$sql = "SELECT * FROM myTable WHERE title IN '" . implode("','", $myarray) . "';"
请注意,您需要首先过滤数组中的SQL注入问题。
答案 3 :(得分:2)
您可以在IN
子句
WHERE
SELECT * FROM myTable WHERE title IN ('hi', 'there', 'everybody');
或
SELECT * FROM myTable WHERE title IN ('.implode(',', $myarray).');