微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在尝试从多个复选框构成一个查询字符串,这些复选框将用于查询数据库.

我有以下表格:

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

从配方中选择*无糖= 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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐