I am trying to form a query string from several flags that will be used to query my database.
I have the following form:
<fieldset data-role="controlgroup">
<input type="checkbox" name="wheat" id="checkbox-1a" class="custom" />
<label for="checkbox-1a">Wheat Allergy</label>
<input type="checkbox" name="yeast" id="checkbox-2a" class="custom" />
<label for="checkbox-2a">Yeast Allergy</label>
<input type="checkbox" name="sugar" id="checkbox-3a" class="custom" />
<label for="checkbox-3a">Sugar Allergy</label>
<input type="checkbox" name="dairy" id="checkbox-4a" class="custom" />
<label for="checkbox-4a">Dairy Allergy</label>
My PHP code is as follows:
if(isset($_POST['wheat']))
{
$str1 = 'wheatfree = 1';
}
if(isset($_POST['yeast']))
{
$str2 = 'yeastfree = 1';
}
if(isset($_POST['sugar']))
{
$str3 = 'sugarfree = 1';
}
if(isset($_POST['dairy']))
{
$str4 = 'dairyfree = 1';
}
$fullsearch = $str1.$str2.$str3.$str4;
$str_SQL = "SELECT * FROM recipes WHERE ".$fullsearch;
echo $str_SQL;
This is kind of what I need, but it is not very graceful.
For example, a sql query looks like this:
SELECT * FROM recipes WHERE sugarfree = 1dairyfree = 1
and if users prefer not to select one, I, of course, get an Undefined variable variable for str that was not selected.
Not sure how to fix this or where to go next. I would like there to be some kind of logic that simply changed the line based on what is being tested on the form, which then generates a nice clean SQL query that I can execute against my DB. But, alas, I am lost: (
Help?