Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Form select option for filtering all results in sql query

So currently I have a form that is being set up as a filter for a sql query:

<form action=" " method="post">
<select  name="filter_1">
<!-- What should be put in the no preference value? -->
<option value=" ">No preference</option>
<option value="Opt_1">Option 1</option>
<option value="Opt_2">Option 2</option>
<option value="Opt_3">Option 3</option>
</select>
<input type="submit" value="Search" name="submit">
</form>

This form upon submission has the option $_POST['filter_1'] submitted and the option is turned into a string.

$filter_1 = mysql_real_escape_string($_POST['filter_1']);

In the sql query, results must have a particular column with a value equal to the select input from above. $sql = ("SELECT * FROM users columnID = '$filter_1' ");

This works perfectly (with multiple filters) for "Option 1", "Option 2", and "Option 3" on all of my tests, but only if all of the filters are set to a value (No preference value doesn't work).

So what should the value of "No Preference" be so that the results include all results from all Options? Or in other words eliminate the filter so it has no effect on the query?

Should I be using a inner or outer join? or checking $_POST['filter_1'] if the not empty?

1 Answer

if ($filter_1 != ' ') {
    $sql = "SELECT * FROM users";
} else {
    $sql = "SELECT * FROM users WHERE columnID = '$filter_1' ";

should work, right?

Worked perfectly! Thanks a bunch!

I modified it to accomodate two blank checks and a complex and/or statement :)

if ($filter_1 != ' ' && $filter_2 != ' ') {
$sql = "SELECT * FROM users WHERE  gender = '$filter_gender' ";
} else {
$sql = "SELECT * FROM users WHERE  gender = '$filter_gender' AND (column1 = '$filter_1' OR  column         = ' $filter_2') ";
}