php三下拉过滤器

时间:2012-06-05 20:28:48

标签: php

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

  • 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>
    ...

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

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

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

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';

有人可以引导我解决这个问题吗?

1 个答案:

答案 0 :(得分: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';