如何结合2种不同的滤镜

时间:2019-05-09 08:20:26

标签: php mysql mysqli filter

我为日期间隔和不同级别(0,1,2)创建了这个简单的过滤器。到目前为止,我已经有了这段代码:

if(isset($_POST['filtersubmit'])){
    $datex = str_replace('/', '-', $_POST['firstdate']);
    $date1 = date("Y-m-d", strtotime($datex));
    $datey = str_replace('/', '-', $_POST['lastdate']);
    $date2 = date("Y-m-d", strtotime($datey));
    $projects = $_POST['projekt'];



    if(isset($date1) && isset($date2)){
        $query = mysqli_query($conn, "SELECT * FROM zapasy WHERE datum BETWEEN 
        '$date1' AND '$date2' ORDER BY id DESC");
    }  


    if($projects == 0){
        $query = mysqli_query($conn, "SELECT * FROM zapasy WHERE projekt = '0' ORDER BY id DESC") or die(mysqli_errno($conn). '-'. mysqli_error($conn));
    } elseif($projects == 1){
        $query = mysqli_query($conn, "SELECT * FROM zapasy WHERE projekt = '1' ORDER BY id DESC") or die(mysqli_errno($conn). '-'. mysqli_error($conn));
    } elseif($projects == 2){
        $query = mysqli_query($conn, "SELECT * FROM zapasy WHERE projekt = '2' ORDER BY id DESC") or die(mysqli_errno($conn). '-'. mysqli_error($conn));
    } 
}

现在,如果我仅选择这些过滤器之一,则效果很好,但是如果我想要间隔和电平过滤器,则它不起作用。我不太确定该怎么做。我真的很感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我会沿用这些内容,使用准备好的语句来保护您免受SQL注入。基本上,如果每个过滤器都存在于WHERE数组中,我们会从每个过滤器中形成$_POST子句,参数和参数类型的数组。然后将它们嵌入查询中,绑定参数并执行查询。

if (isset($_POST['filtersubmit'])) {
    $params = array();
    $paramtypes = array();
    $wheres = array();
    if (isset($_POST['firstdate'], $_POST['lastdate'])) {
        $date1 = date_create_from_format('m/d/Y', $_POST['firstdate']);
        $date2 = date_create_from_format('m/d/Y', $_POST['lastdate']);
        if (!empty($date1) && !empty($date2)) {
            array_push($params, $date1->format('Y-m-d'), $date2->format('Y-m-d'));
            array_push($paramtypes, 's', 's');
            array_push($wheres, 'datum BETWEEN ? AND ?');
        }
    }
    if (isset($_POST['projekt'])) {
        $project = $_POST['projekt'];
        if (is_numeric($project) && $project >= 0 && $project <= 2) {
            array_push($params, $project);
            array_push($paramtypes, 'i');
            array_push($wheres, 'projekt = ?');
        }
    }
    $sql = 'SELECT * FROM zapasy';
    if (count($wheres)) {
        $sql .= ' WHERE ' . implode(' AND ', $wheres);
    }
    $sql .= ' ORDER BY id DESC';
    $stmt = $conn->prepare($sql) or die($conn->error);
    if (count($wheres)) {
        $stmt->bind_param(implode('', $paramtypes), ...$params);
    }
    $stmt->execute() or die($stmt->error);
    // bind results
    $stmt->bind_result(/* variables corresponding to each field in SELECT */);
    while ($stmt->fetch()) {
        // do something with the data
    }
}