从多个复选框形成查询字符串

时间:2011-02-20 19:03:12

标签: php sql checkbox

我正在尝试从多个复选框中形成一个查询字符串,用于查询我的数据库。

我有以下表格:

            <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>

我的PHP代码如下:

        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查询如下所示:

SELECT * FROM recipes WHERE sugarfree = 1dairyfree = 1

如果用户选择不选择其中一个,我当然会为未选择的str获取未定义的变量错误。

不确定如何解决这个问题或下一步该做什么。我想在这里有一些逻辑,只是根据表单上检查的内容修改字符串,然后形成一个很好的干净的SQL查询,我可以对我的数据库运行。但是我很遗憾:(

帮助?

2 个答案:

答案 0 :(得分:3)

继Dave的回答:

$options = Array();
$ingredients = Array('wheat', 'yeast', 'sugar', 'dairy');

foreach ($ingredients as $i)
   if (isset($_POST[$i]))
      $options[] = $i . 'free = 1';

$sql = "SELECT * FROM recipes";
if (count($options))
   $sql .= " WHERE " . implode(' AND ', $options);

echo $sql;

但为什么不使用复选框的value属性?

<input type="checkbox" name="ingredients[]" value="wheat" />
<input type="checkbox" name="ingredients[]" value="sugar" />

然后:

$options = Array();
foreach ($_POST['ingredients'] as $i)
   $options[] = $i . 'free = 1'; // don't forget to escape $i somehow!

$sql = "SELECT * FROM recipes";
if (count($options))
   $sql .= " WHERE " . implode(' AND ', $options);

echo $sql;

答案 1 :(得分:2)

这个怎么样:

$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;