从多个$ _GET构建WHERE子句

时间:2013-09-12 17:43:08

标签: php mysql sql where

我目前正在尝试编写从$ _GET变量生成的复杂MySQL WHERE子句(它们本身来自选择下拉列表)。首先,一些代码让你知道我在说什么:

    if(!isset($_GET['order'])){
        $order= 'start asc';
    } elseif ($_GET['order'] == "dateasc") {
        $order= 'start asc';
    } elseif ($_GET['order'] == "titleasc") {
        $order= 'title asc';
    } elseif ($_GET['order'] == "titledesc") {
        $order= 'title desc';
    };


    if(!isset($_GET['cat'])){
        $cat= '0';
    } else  {
        $cat = $_GET['cat'];
    };


    if(!isset($_GET['loc'])){
        $loc= '0';
    } else  {
        $loc = $_GET['loc'];
    };


    if (isset($_GET['sd']) || isset($_GET['ed']) || isset($_GET['cat']) || isset($_GET['loc']) || isset($_GET['order']) ) {
        $where = 'WHERE ';

        if (isset($_GET['sd'])) {
            $where .= "start = " . $_GET['sd'];
        };

        if (isset($_GET['ed'])) {
            $where .= "AND end = " . $_GET['ed'];
        };

        if (isset($_GET['cat'])) {
            $where .= "AND category = " . $_GET['cat'];
        };

        if (isset($_GET['loc'])) {
            $where .= "AND location = " . $_GET['loc'];
        };
    };


    $result = mysql_query("SELECT * FROM " . TABLE . $where . " ORDER BY " . $order);

显然这不起作用,否则我不会在这里。 :)基本上,我有4个变量,我想有条件地用于我的查询中的排序:开始日期,结束日期,类别和位置。我的问题是所有这4个可能并不总是被使用..所以鉴于上面的例子,可能有人选择一个类别($ cat)但不是开始日期($ sd)......这意味着我的WHERE子句以'AND'开头,显然无效。那么如何根据可能使用或不使用的变量构建查询?

我真的觉得我正在过度思考这个问题,我害怕编写9000行isset测试来解释$ _GET变量用法的每个组合。当然有一种简单的方法可以从多个$ _GETs构建一个WHERE子句,每次都可以使用或不使用..?我已经尝试了谷歌搜索,但只能找到建议使用框架来构建复杂查询的解决方案,这似乎过于......笨重......对于这样一个简单的问题。

2 个答案:

答案 0 :(得分:4)

如果你只是担心有一个以AND开头的where子句,你可以添加1 = 1来代替没有过滤器。

WHERE 1=1

然后,如果您有任何过滤器,它将如下所示:

WHERE 1=1 AND col1=? AND col2=?

答案 1 :(得分:-1)

这可能不是最干净的解决方案,但理解和实施应该相当简单。

if (isset($_GET['sd']) || isset($_GET['ed']) || isset($_GET['cat']) || isset($_GET['loc']) || isset($_GET['order']) ) {
    $where = 'WHERE ';

    if (isset($_GET['sd'])) {
        if(strlen($where) > 6) {
           $where .= " AND ";
        }
        $where .= "start = " . $_GET['sd'];
    }

    if (isset($_GET['ed'])) {
        if(strlen($where) > 6) {
           $where .= " AND ";
        }
        $where .= "end = " . $_GET['ed'];
    }

    if (isset($_GET['cat'])) {
        if(strlen($where) > 6) {
           $where .= " AND ";
        }
        $where .= "category = " . $_GET['cat'];
    }

    if (isset($_GET['loc'])) {
        if(strlen($where) > 6) {
           $where .= " AND ";
        }
        $where .= "location = " . $_GET['loc'];
    }
}
相关问题