0

我试图用数组填充查询。据我所知,我可以显示带有函数的数组,foreach();但我无法将它放在 mysql 查询中我试图做这样的事情:

<?php
$arr = array("arr_1", "arr_2", "arr_3", "arr_4");

$query = mysql_query("SELECT * FROM users WHERE user = '1'".
foreach($arr as $arr) {
    echo "AND user = '".$arr++."'";
}
." ORDER BY id";
?>

脚本必须将其显示为:
$query = mysql_query("SELECT * FROM users WHERE user = '1' AND user = 'arr_1' AND user = 'arr_2' AND user = 'arr_3' AND user = 'arr_4'");

但这不起作用,因为您无法foreach()放入mysql_query();
所以我需要的是做同样事情的脚本(在查询字符串中显示数组)

谢谢。

4

2 回答 2

2

如果要从数组中添加多个条件,请进行连接而不是回显

<?php
$arr = array("arr_1", "arr_2", "arr_3", "arr_4");

$query = mysql_query("SELECT * FROM users WHERE user = '1'";
foreach($arr as $id) {
    $query .= "AND user = '".$id."'";
}
$query .= " ORDER BY id";
?>
于 2013-03-18T17:34:16.330 回答
0

不是最好的解决方案,而是替代方案:

$arr = array("arr_1", "arr_2", "arr_3", "arr_4");

$arr_string="'".implode("','", $arr)."'"; // surround values in quotes

$query = mysql_query("SELECT * FROM users WHERE user IN (".$arr_string.") ORDER BY id";
于 2013-03-18T17:44:29.383 回答