PDO multi-Filter sql query

前端 未结 2 1365
终归单人心
终归单人心 2021-01-22 08:14

Is there a simpler way for me to code this and perform the same thing without having to have so many queries? Im trying to add pagination (not included in code here) and it work

2条回答
  •  迷失自我
    2021-01-22 08:45

    And My Second thought:

    $sql = 'SELECT * FROM _product JOIN _module_type ON module_type = module_id WHERE';
    if(!empty($filter) || !empty($status)){
        $sql .= ' module_type = :filter '.(!empty($filter) && !empty($status) ? 'AND' : 'OR').' product_status = :status';
        $sth = $link->prepare($sql);
        $sth->bindValue(':filter', $filter);
        $sth->bindValue(':status', $status);
    }else{ $sth = $link->prepare($sql); }
    $result = $sth->execute();
    

    It needs testing and as truth said you might not need the OR but that is upto exactly how your form and filtering works tbh, but I am gonna leave it at that it should give you pointers to move to the next stage.

    Edit again:

    Couldn't help myself, here is a third possibility:

    $params = array();
    $where = array();
    
    if(!empty($filter)){
        $params[':filter'] = $filter;
        $where[] = 'module_type = :filter';
    }
    if(!empty($status)){
        $params[':status'] = $status;
        $where[] = 'product_status = :status';
    }
    
    $sql = 'SELECT * FROM _product JOIN _module_type ON module_type = module_id'.(sizeof($where) > 0 ? ' WHERE '.implode(' AND ', $where) : '');
    
    $sth = $link->prepare($sql);
    foreach($params as $k=>$v) $sth->bindValue($k, $v);
    $result = $sth->execute();
    

提交回复
热议问题