Here is the updated code.
classifieds table
id | title | description | state_id | city_id |
1 Ford | ford for sell| 1 | 1
2 Ford | ford explorer| 2 | 1
state table
id | name |
1 Texas
2 Arizona
city table
id | name | state_id
1 Arlington 1
2 Globe 2
The code that does the search and prints the results is all here:
So this file called search.php
enter <?php
$conn = mysql_connect('localhost', 'root','');
$db = mysql_select_db('files',$conn);
$input = $_GET['query'];
$state = $_POST['state'];
$city = $_POST['city'];
if (isset($input) && $input != "" ) {
$select = "SELECT * FROM classifieds";
$where = " WHERE (title like '%" . $input . "%' OR description like '%" . $input .
"%')";
if (!empty($city)) {
$select .= " LEFT JOIN city ON classifieds.city_id=city.id";
$where .= " AND city.name = '" . $city . "'";
}
if (!empty($state)) {
$select .= " LEFT JOIN state ON classifieds.state_id=state.id";
$where .= " AND state.name = '" . $state . "'";
}
$q = $select . $where . ' ORDER BY date DESC';
$r = mysql_query($q);
$rows = mysql_num_rows($r);
}
echo $rows; ?> Search Results For: <?PHP echo $input;
if ($rows > 0) {
while ($row = mysql_fetch_array($r, MYSQL_ASSOC)) {
$description = $row['description'];
echo " <tr >
<td ><a href='classified-" . $row['adid'] . ".htm' >" . $row['title'] . "</a><br />
<span><em><a href='category-" . $cat . ".php'>" . $catname . "</a></em><br/>" .
$description . "...</span></td>
</tr>
";
}
}
?>
<form action="search.php" method="get">
<input type="text" name="query" />
<input type="submit" name="Submit" value="Search" />
<select name="state" >
<option value="null"></option>
<?php
//POPULATE DROP DOWN MENU WITH STATES FROM A GIVEN REGION, COUNTRY
$sql = "SELECT id, statename FROM state";
$states = mysql_query($sql,$conn);
while($row = mysql_fetch_array($states))
{
echo ("<option value=".$row[id]." >$row[statename]</option>");
}
?>
</select>
<select name="city" >
<option value="null"></option>
<?php
$sql = "SELECT id, city FROM city ";
$cities = mysql_query($sql,$conn);
while($row = mysql_fetch_array($cities))
{
echo ("<option value=".$row[id].">$row[city]</option>");
}
?> here
You basically need to check if
stateand/orcityare set (by the way, you haveGETset as a method in form, yet you check$_POSTfor city and state – is that correct?) and add them to sql query accordingly:Note the parentheses for title and description – without them OR would take precendence over AND.
As a sidenote, you don’t need to query database twice for the same data.