我正在尝试从多个复选框构成一个查询字符串,这些复选框将用于查询数据库.
我有以下表格:
<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>
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;
这是我所需要的,但是不是很优雅.
首先,SQL查询如下所示:
从配方中选择*无糖= 1无乳= 1
如果用户选择不选择一个I,则对于未选择的str当然会出现Undefined variable错误.
不太确定如何解决此问题或下一步去哪里.我在这里想要一些逻辑,该逻辑只是根据在表单上检查的内容来修改字符串,然后形成一个可以针对我的数据库运行的漂亮的干净SQL查询.但是a,我迷路了:(
救命?
解决方法:
这个怎么样:
$options = array();
if(isset($_POST['wheat']))
{
$options[] = 'wheatfree = 1';
}
if(isset($_POST['yeast']))
{
$options[] = 'yeastfree = 1';
}
if(isset($_POST['sugar']))
{
$options[] = 'sugarfree = 1';
}
if(isset($_POST['dairy']))
{
$options[] = 'dairyfree = 1';
}
$fullsearch = implode(' AND ', $options);
$str_sql = "SELECT * FROM recipes";
if ($fullsearch <> '') {
$str_sql .= " WHERE " . $fullsearch;
}
echo $str_sql;