SQL Query中的数组?

nja*_*jak 9 php mysql

我在WHERE子句中使用数组创建SQL查询时遇到问题.

例如:

我的阵列:

$myarray[1] = "hi";
$myarray[2] = "there";
$myarray[3] = "everybody";
Run Code Online (Sandbox Code Playgroud)

我的MySQL声明:

SELECT * FROM myTable WHERE title='".$myarray[]."'
Run Code Online (Sandbox Code Playgroud)

有没有办法实现这一点?我自己解决了这个问题:

for(...) {
$where = $where." title='".$myarray[$count]."' OR ";
}
$where = substr($where , 0, -3);
.....
SELECT * FROM myTable WHERE ".$where."
Run Code Online (Sandbox Code Playgroud)

但是如果我的数组中有数千个条目,那么SQL语句会变得太大而且很慢,对吧?

谢谢

Tim*_*Tim 14

你可以使用mysql的IN函数

编辑:正如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);
Run Code Online (Sandbox Code Playgroud)


You*_*nse 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);
Run Code Online (Sandbox Code Playgroud)