I am trying to build a filtering system that shows results based on text input and checkbox options selected by a user.
My database currently has 3 tables
table 1 : brunches
table 2 : vibes
table 3 : cuisines
brunches contains a list of restaurants, and in the
brunchesvibescontains vibes and
brunchescuisinestables contains the food that the restaurants from
brunches` offers.
So for example
Table 1 - Brunches
id Name
1 Jamies Brunch
2 Roka
3 Mcdonalds
Table 2 - Vibes
id vibe brunchid
1 Arty 1
2 Luxury 1
3 Trendy 3
Table 3 - Cuisines
id cuisines brunchid
1 BBQ 1
2 Japanese 1
3 British 3
As you can see all the tables match up via brunchid.
What I am trying to achieve is i have a bunch of checkboxes in a form, which contains a list of 'vibes' and 'cuisines', when a user checks the vibes and cuisines they want displayed, it should then run a query and show only those results.
this is the php code so far, however it doesn't work - when i select multiple options, it returns an sql error, because it is just doing an AND statement, that being said, I'm not sure if the way i've got it searching the vibes table is correct... and i'm not sure how to add OR statements when there are multiple options selected.
$type = $this->input->post("type");
$name = $this->input->post("brunchname");
$vibes = $this->input->post("vibes");
$cuisines = $this->input->post("cuisines");
$range = $this->input->post("range");
$sqlQuery = "SELECT b.*, host,
FROM brunches b
LEFT JOIN hosts ON hosts.id = b.hostid ";
if(! empty($vibes)) {
foreach ($vibes as $v):
$sqlQuery .= "WHERE b.id in (
select bv.brunchid from brunchvibes bv where bv.vibe = '$v')";
endforeach;
}
if(! empty($cuisines)) {
foreach ($cuisines as $c):
$sqlQuery .= "WHERE b.id in (
select b.brunchid from brunchcuisines bc where bc.cuisine = '$c')";
endforeach;
}
if(! empty($name)) {
$sqlQuery .= "name LIKE '%$name%')";
endforeach;
}
$sqlQuery .=" AND approved ='1'";