I currently have a large table in MySQL with several fields. I am currently attempting to allow the user to filter by each field, via Select Boxes.
I have 4 fields: School, Division and State.
I have no problem, using PHP, on how to filter based on which option the user selects in the select box.
For example, if these 3 are submitted:
<select id="school">
<option value="13">John Brown School</option>
</select>
<select id="division">
<option value="I">I</option>
</select>
<select id="state">
<option value="NY">New York</option>
</select>
I would be able to query based on each option, like:
$school= $_POST['school'];
$division= $_POST['division'];
$state = $_POST['state'];
Query: SELECT * from table WHERE school=$school AND division=$division and state=$state
However, if I want to have an “All” option (in the select box), how would I implement this into the query or the WHERE clause, so that it does not filter that particular field?
You should simply make an option that you specifically look for. In fact, in this case it sounds like the best choice would be to make your select boxes have an “All” option, or just leave them blank. The blank choice can be your default. I would have it set up as:
Now, when setting up your query variables, you do this:
Now if any select options get selected with the blank values (ie. use all), they won’t be part of the WHERE clause.
You are open to SQL injection attacks if you don’t escape your incoming $_POST data as well, so one thing you need to do is run mysql_real_escape_string() on your $_POST values, which I added in to the example. It sounds like you’re already aware of that though.