0

我有一个名为分类的表,它包含以下内容:

  • ID
  • 标题
  • 描述
  • state_id
  • city_id
  • cat_id

这是从数据库动态填充的。

<form name="theForm" method="post" action="advanced_search.php">
    <input type="submit" name="Submit" value="Search" />
    <select name="categories" >
        <option value=""> Select Category</option>
    </select>
    <select name="state" >
        <option value=""> Select state</option>
    </select>
    <select name="city" >
        <option value=""> Select city</option>
    </select>
    ...

当我选择一个类别并单击搜索时,将显示该类别的结果。如果我选择一个类别和一个状态,那么我希望它过滤到指定的类别和状态。如果选择了一个城市,也会发生同样的情况。

例如:如果我选择明尼阿波利斯市的就业类别,则搜索应过滤到该城市的所有就业。

使用下面的代码,它需要选择所有下拉列表才能使过滤器正常工作。如果我想在指定状态下显示一个类别的所有结果怎么办?如果我只想按类别过滤怎么办?

if (isset($_POST['Submit'])) {
    $state = $_POST['state'];
    $city = $_POST['city'];
    $categories = $_POST['categories'];

    $select = "SELECT * FROM classifieds";
    $where = " WHERE ( authorized = '1')";

    $where .= " AND (cat = '" . $categories . "' AND state_id = '" . $state . "' AND city_id = '" . $city . "')";

    $where .= " AND (state_id = '" . $state . "' )";
    $where .= " AND (city_id = '" . $city . "' )";
    $q = $select . $where . ' ORDER BY date DESC';

有人可以帮我完成这个吗?

4

1 回答 1

2

只有在他们选择了某些东西时才添加 where 子句:

$select = "SELECT * FROM classifieds";
$where = " WHERE ( authorized = '1')";
if($categories) {
    $where .= " AND (cat = '" . $categories . "' )";
}
if($state) {
    $where .= " AND (state_id = '" . $state . "' )";
}
if($city) {
    $where .= " AND (city_id = '" . $city . "' )";
}
$q = $select . $where . ' ORDER BY date DESC';
于 2012-06-05T20:32:39.660 回答