使用PHP参数构建mySQL查询 - "首先AND"

时间:2016-09-29 20:08:28

标签: php mysql

我正在尝试使用php构建一个sql查询,其中每个GET变量(如果设置)都会附加到查询中。例如:

$dbQuery = "SELECT * FROM orders WHERE deleted = 0 AND ({$dueQ} {$paidQ} {$completedQ} {etc. etc. etc.}) ";

每个参数的创建方式如下:

$due = $_GET['due'];
if (isset($due)) {
    $dueQ = " AND due = '0'";
}

所以我检查是否设置了每个get参数,如果是,则将该字符串添加到查询中。

我的问题是...... 如何创建查询,使第一个参数不以" AND"?开头?由于我不知道哪个是要添加到查询中的第一个参数,因此我无法找到一种方法来解释它不是以" AND"开头。现在查询读取" AND 到期=' 0'与...&#34 ;.有意义吗?

2 个答案:

答案 0 :(得分:3)

您可以将参数添加到数组中,然后implode()AND作为粘合剂添加:

$params = array();
if (isset($_GET['due']))
    $params[] = "due = '0'";

if (isset($_GET['paid']))
    $params[] = "paid = '0'";

...etc...

$dbQuery = "SELECT ... WHERE deleted = 0 AND ".implode(' AND ', $params);
//SELECT ... WHERE deleted = 0 AND due = '0' AND paid = '0'

答案 1 :(得分:1)

使用布尔变量检查条件是否已经满足,并根据布尔变量的状态,逐步构造查询,如下所示:

$dbQuery = "SELECT * FROM orders WHERE deleted = 0";

$flag = false;

$due = $_GET['due'];
if(isset($dueQ)){
    $dbQuery .= " AND due = '0'"; 
    $flag = true;
}

if(isset($paidQ)){
    if($flag){
        $dbQuery .= " something = 'something'";
    }else{
        $dbQuery .= " AND somethingElse = 'somethingElse'";
        $flag = true;
    } 
}

if(isset($completedQ)){
    if($flag){
        $dbQuery .= " something = 'something'";
    }else{
        $dbQuery .= " AND somethingElse = 'somethingElse'";
        $flag = true;
    } 
}

// etc.