I’m storing a bunch of data for communities in MySql
My initial communities table has these fields:
- id (primary key)
- name
- logo
- map
- description
I’m then storing different data for each community in other tables like this:
Table: community_amenities
- id (primary key)
- community – this references the id
field from the communities table
above - amenity – A comma separated list of
amenities that this community has –
2,3,5,7,8 etc – these numbers
reference IDs from another table
Table: community_prices
- id (primary key)
- community – this references the id
field from the communities table
above - prices – A comma separated list of
price ranges for homes in the
community these numbers reference
IDs from another table
Table: community_products
- id (primary key)
- community – this references the id
field from the communities table
above - products – A comma separated list of
types of homes in the community
these numbers reference IDs from
another table
I then have a form with a number of checkboxes that let users choose the amenities, price ranges and products that they are interested in like this:
<input name='amenities[]' type='checkbox' value='1'/>
<input name='amenities[]' type='checkbox' value='2'/>
<input name='amenities[]' type='checkbox' value='3'/>
<input name='amenities[]' type='checkbox' value='4'/>
<input name='amenities[]' type='checkbox' value='5'/>
<input name='prices[]' type='checkbox' value='1'/>
<input name='prices[]' type='checkbox' value='2'/>
<input name='prices[]' type='checkbox' value='3'/>
<input name='prices[]' type='checkbox' value='4'/>
<input name='prices[]' type='checkbox' value='5'/>
so my question is…
I need to grab the items they have selected from the form and query the database to display communities that match the criteria.
I can do it fine with 1 of the fields like this:
$priceArray = $_POST['price'];
$selectPrice = join(',',$priceArray);
$sql = mysql_query("SELECT * FROM community_prices WHERE prices IN ($selectPrice)");
But i need to do it with all the tables and I need to return only communities that meet all the selected criteria.
I’ve tried a whole wack of different methods (UNION, JOIN) with no luck. Any help would be greatly appreciated.
So you want all the communities that match the given price, amenity, and product criteria? This is all under the assumption that the IN statement you listed in your example would create a valid match.
Obviously you’ll need to adjust any table/column names I got wrong. You should also add conditional logic to only introduce the INNER JOINs and WHERE conditions that are necessary for your specific query. For example, do not include the INNER JOIN or WHERE condition for amenity if you the user didn’t select amenity as a criteria.