Checkbox filter

Post here if you need help with SQL.
Post Reply
Smithers
Posts: 8
Joined: Mon Feb 06, 2012 3:09 pm

Checkbox filter

Post by Smithers »

Hi Jacek,
I was searching through you site and was looking for a tutorial on sql checkbox filter.
I'd like to display certain results based on checkboxes:

Thanks,
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: Checkbox filter

Post by Temor »

You're gonna have to be a bit more specific on what you want and what you've tried so far.
Smithers
Posts: 8
Joined: Mon Feb 06, 2012 3:09 pm

Re: Checkbox filter

Post by Smithers »

Hi Temor,
here's what I've got so far:

[syntax=php]$sql = "SELECT * FROM house";

$result = mysql_query($sql);
if(!$result)
{
echo 'no houses are available yet.';
}
else
{
if(mysql_num_rows($result) == 0)
{
echo 'no houses are available yet.';
}
else
{

echo '<table border="1">
<tr>
<th>state</th>
<th>type</th>
<th>city</th>
<th>city area</th>
<th>street</th>
<th>housenumber</th>
</tr>';

while($row = mysql_fetch_assoc($result))
{
echo '<tr>';
echo '<td>';
echo '<h3><a href="edit_event.php?id=' . $row['id'] . '">' . $row['state'] . '</a><br /><h3>';
echo '</td>';
echo '<td>';
echo $row['type'] ;
echo '</td>';
echo '<td>';
echo $row['city'] ;
echo '</td>';
echo '<td>';
echo $row['city area'] ;
echo '</td>';
echo '<td>';
echo $row['street'] ;
echo '</td>';
echo '<td>';
echo $row['housenumber'] ;
echo '</td>';
echo '</tr>


';


}
}
}
?>
[/syntax]

What I'd like to do is that I see all the results if I haven't activated any checkbox, however if I have type: house, flat and I check flat, I want to see flats only. The second I'd like to archive is that certain city areas are visible only if a certain city is selected. Let's say I check New York, then I have the option to check Bronx, Manhattan, etc.), If L.A is selected I have the option to check areas in L.A

I did write a code for a filter but this one turned out to be an extremely large code and I am almost certain that the code can be quite short as well. Also I didn't figure out how to show results immediately (only through submit).

Would be great if you could direct me to an example.

Many Thanks,
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: Checkbox filter

Post by Temor »

Well, the first solution that comes to mind is to create a "dynamic" SQL statement.
[syntax=php]$sql = "SELECT `type`,`state` FROM house WHERE `type` = '{$_POST['type']} AND `state` = '{$_POST['state']}'' ";[/syntax]

This would only select results that match the chosen type and state.

However, this will only show the results after you've submitted the form. To get it to show results without refreshing you would need to look into Javascript. Either Ajax or jQuery I suppose. I'm not very good with either, so I'll leave that to someone more qualified.
Post Reply