在第1页上我有一个表单,然后在第2页上是处理器文件,我想根据第1页上选中的复选框来选择记录。
<form action="output.php" method="post">
<input type="checkbox" id="" class="" name="check_list[]" value="something" />
<input type="checkbox" id="" class="" name="check_list[]" value="something else" />
<input type="checkbox" id="" class="" name="check_list[]" value="yet another thing" />
<input type="checkbox" id="" class="" name="check_list[]" value="one more thing" />
<input type="checkbox" id="" class="" name="check_list[]" value="some name" />
<input type="checkbox" id="" class="" name="check_list[]" value="some other name" />
<input type="submit" value="Submit" name="submit">
</form>
下面的foreach可以显示被检查的所有内容的所有值,但我不知道如何进一步进入我的SQL选择语句以选择具有该名称的列字段的所有记录。
foreach($_POST['check_list'] as $check) {
echo $check . '<br>';
}
比如在一个名为stuff的表中有这些字段
id, first_title, second_title
所以我想做下面的,但显然不是这样写的。这是我需要帮助的部分。
SELECT * FROM stuff WHERE first_title = $check or second_title = $check
让我们进一步说这些记录存在于表中…
id first_title second_title
-----------------------------------------
1 something something else
2 yet another thing one more thing
3 some name some other name
然后假设这些复选框被选中:
<input type="checkbox" id="" class="" name="check_list[]" value="something" />
<input type="checkbox" id="" class="" name="check_list[]" value="one more thing" />
所以我想要发生的是我的select语句选择记录1和记录2,而不是记录3,因为"某事"在第一个记录的first_title列中,而"one more thing"在第二个记录的second_title中,并且没有检查第三个记录。
我希望我提供了所需的所有细节。
使用SQL IN
操作符测试列是否在值列表中。下面是如何用MySQLI编写它:
$in_str = implode(', ', array_map(function($title) use ($con) {
return "'" . $con->real_escape_string($title) . "'";
}, $_POST['check_list']));
$sql = "SELECT * FROM stuff WHERE first_title IN ($in_str) OR second_title IN ($in_str)";
$result = $con->query($sql);
在代码中试试这个动态where条件
<?php
$arr_where = array();
foreach($_POST['check_list'] as $check) {
$arr_where[] = " first_name='$check' OR last_name='$check' ";
}
$where_text = implode("OR", $arr_where);
$sql = "SELECT * FROM stuff WHERE ".$where_text;
?>