所以我正在尝试根据用户的输入创建MySQL查询。我有很多复选框(大约50个),所以我不想单独进行。这里只是我的几个复选框:
<input type="checkbox" name="check_list[]" value="ki67" /> ki67<br><br>
<input type="checkbox" name="check_list[]" value="myc" /> myc<br><br>
<input type="checkbox" name="check_list[]" value="mta1" /> mta1<br><br>
<input type="checkbox" name="check_list[]" value="mvd/cd34" /> mvd/cd34<br><br>
然后我通过PHP运行它们告诉用户已检查的内容:
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
echo $check . "<br>";
}
}
现在我想通过MySQL进程运行它们来显示已选择的行数。这是我的代码:
<?php
//perform database query
$query = "SELECT COUNT(*) ";
$query .= "FROM testdata ";
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
$query .= "WHERE rd_$check = 1";
}
}
然后:
$result = mysqli_query($link, $query);
if (!$result) {
die("Database query failed.");
}
当我尝试检查多个盒子时出现问题。我不知道如何将更多内容连接到$query
。该命令必须类似于:
SELECT COUNT(*) FROM testdata WHERE rd_ki67 = 1 AND rd_myc = 1 AND ...;
有谁知道怎么做?
答案 0 :(得分:1)
if(!empty($_POST['check_list'])) { foreach($_POST['check_list'] as $check) { $query .= "WHERE rd_$check = 1"; } }
这导致包含多个WHERE
子句(WHERE condition WHERE condition WHERE ...
)的查询字符串不正确。
一种解决方案是让PHP的implode()函数将子表达式粘合在一起:
if(!empty($_POST['check_list'])) {
$wheres = array();
foreach($_POST['check_list'] as $check) {
$wheres[] = "rd_$check = 1";
}
$query .= 'WHERE ' . implode (' AND ', $wheres);
}
结束AND
链的另一种方法是在最后添加一个始终为真的表达式:
if(!empty($_POST['check_list'])) {
$query .= 'WHERE ';
foreach($_POST['check_list'] as $check) {
$query .= "rd_$check = 1 AND ";
}
$query .= '1';
}