Page 1 of 1
Checkbox filter
Posted: Mon Aug 20, 2012 9:41 am
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,
Re: Checkbox filter
Posted: Mon Aug 20, 2012 3:00 pm
by Temor
You're gonna have to be a bit more specific on what you want and what you've tried so far.
Re: Checkbox filter
Posted: Tue Aug 21, 2012 9:58 am
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,
Re: Checkbox filter
Posted: Tue Aug 21, 2012 12:18 pm
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.