0

I have a table called classifieds and it contains the following:

  • id
  • title
  • description
  • state_id
  • city_id
  • cat_id

This is dynamically populated from database.

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

When I select a category and click search, the result for that category will show up. If I select a category and a state then I want it to filter to a specified category and state. The same should occur if a city is selected.

EX: If I select employment category in Minneapolis city, then the search should be filtered to all employments in that city.

With the code bellow it requires to select all the dropdowns to get the filter working. What if I want to show all results of a category in a specified state? What if I want to filter by category only?

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

Can someone walk me through this?

4

1 に答える 1

2

Only add the where clauses if they've selected something:

$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 に答える