php - 如何搜索在 HTML 复选框中选择的多个输入(分别)?

标签 php html mysqli

我有一个关于为同一个表列构造具有多个输入的 MySQLi 查询的简单问题。基本上,我希望人们能够显示 (1) 和 (2) 与 (1 和 2) 的结果,但我一直遇到问题。

HTML:

<form method="get" action="page.php">
  <ul>
    <li><input type="checkbox" name="PT1" value="Condo">Condo</li>
    <li><input type="checkbox" name="PT2" value="Single Family">Single Family</li>
  </ul>
</form>

PHP:

if($_GET['PT1'] == "Condo") {
    $PropType1 = "(property_type = 'Condo') AND ";
}

if($_GET['PT2'] == "Single Family") {
     $PropType2 = "(property_type = 'Single Family') AND ";
}

$setPropType = $PropType1 . $PropType2;

MySQLi 语句:

$customSelectSQL = "SELECT * FROM $listingsTable WHERE $setPropType (listing_active = 'yes')";

我遇到了一个问题,如果同时检查了它们,查询将不执行任何操作,我得到的结果为零。但当它们被单独选择时,效果很好。

我认为发生的事情是数据库正在搜索等于两个输入的属性,而不是分别等于每个输入并为每个单独的输入返回每一行。有道理吗?

我猜这是封装之类的问题,但是当我搜索“MySQL SELECT Multiple”或“MySQLi encapsulation”时,我得到了一堆不太有用的示例。

提前致谢!

最佳答案

最好将它们放入数组中,然后将它们内爆。
编辑:同样,您应该在搜索 property_type 时使用 OR,因为您不会找到 1 行具有 2 个不同的 property_type 作为 AND(因为它是一列)。

像这样的东西:

$where = array();
if($_GET['PT1'] == "Condo") {
        $where[] = "(property_type = 'Condo')";
}
if($_GET['PT2'] == "Single Family") {
        $where[] = "(property_type = 'Single Family')";
}   

$where_string = implode(' OR ', $where);
$customSelectSQL = "SELECT * FROM $listingsTable WHERE (listing_active = 'yes') AND ($where_string)";

edit2: 为了防止出现空数组,只需添加 if(如果只需要一个 AND)或添加额外的数组来连接 AND 语句,例如:

$where_or = array();
$where_and = array();
$where_and[] = "(listing_active = 'yes')";
if($_GET['PT1'] == "Condo") {
        $where_or[] = "(property_type = 'Condo')";
}
if($_GET['PT2'] == "Single Family") {
        $where_or[] = "(property_type = 'Single Family')";
}   

if(count($where_or) > 0) {
    $where_and[] = '('.implode(' OR ', $where_or).')';
}

if(count($where_and) > 0) {
    $where_string = implode(' AND ', $where_and);
} else {
    $where_string = '';
}
$customSelectSQL = "SELECT * FROM $listingsTable $where_string";

关于php - 如何搜索在 HTML 复选框中选择的多个输入(分别)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29997692/

相关文章:

html - 嵌套 HTML- anchor 标签

php - 它在 php/html 中错误地输出详细信息

包含意外值的 PHP 对象属性

php - 尝试在 <select> 中显示数据库字段

php - Laravel 在 url 字符串中更改获取参数并返回

html - 如何在 Django 中将按钮单击重定向到另一个 URL?

PHP 与 bind_param() 相关的问题;

php - dropzone.js 未上传

php - 使用 array_map() 访问一级键而不调用 `array_keys()`

html - Windows 8 上的 Chrome 中的输入边框被截断