这是我表单中的$ _POST数组。
Array ( [prescribedid] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 9 [4] => 13 )
我想为数组中的任何项创建一个选择。我已经写了这个,它产生了正确的SELECT,但if()消除了尾随的OR使它变得笨重。
$query = "SELECT * ";
$query .= "FROM prescribed WHERE ";
for($i=0; $i<count($_POST["prescribedid"]); $i++) {
$query .= "prescribedid={$_POST['prescribedid'][$i]} ";
if($i < (count($_POST["prescribedid"])-1)) {
$query .= "OR ";
}
}
它产生了这个:
SELECT * FROM prescribed WHERE prescribedid=1 OR prescribedid=2 OR prescribedid=3 OR prescribedid=9 OR prescribedid=13
是否有另一种方法可以对SELECTS进行分组或编写FOR()以使其更清晰,即没有最后的IF()。
答案 0 :(得分:8)
$values=implode(",",$_POST["prescribedid"]);
$query = "SELECT * FROM prescribed WHERE prescribedid IN ($values)";
Sanitization 就在你身上:))
答案 1 :(得分:4)
使用MySQL IN子句
$ids = implode(",",$_POST["prescribedid"]);
$query = "SELECT * FROM prescribed WHERE prescribedid IN ($ids)";
答案 2 :(得分:4)
您好您可以使用In
condition
。使用imploade
函数查找逗号seoarated值
$data = array('prescribedid'=>array(1,2,3,9,14));
$query = 'SELECT * FROM prescribed WHERE prescribedid IN (';
$query .= implode(',',$data['prescribedid']).')';
echo $query ;
输出
SELECT * FROM prescribed WHERE prescribedid IN (1,2,3,9,14)
答案 3 :(得分:2)
您可以在此处使用IN子句。
$query = "SELECT * FROM prescribed WHERE prescribedid IN ".implode(',', $_POST["prescribedid"]);