我试图用数组填充查询。据我所知,我可以使用函数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();
中
所以我需要的是执行相同操作的脚本(在查询字符串中显示数组)
感谢。
答案 0 :(得分:2)
如果要从数组中添加多个条件,请执行连接而不是echo
<?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";
?>
答案 1 :(得分: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";