SQL and PHP filter

前端 未结 1 792
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-27 08:51

I have a SQL table with model year from and model year to, in filter I need to select only one parameter year and I want to get all models which are in that year gap.

         


        
1条回答
  •  一整个雨季
    2021-01-27 09:10

    Seem like you don't have put the full request, but you should be able to do something with this :

    WHERE
        $year >= `from`
        AND $year <= coalesce(`to`, 9999)
    

    The coalesce() is here in case you don't have a to date but a NULL instead (still in production).


    Here is the full version : (As I really can't stand mysqli_* function, and they are not well suited/secure for this use case, This is a PDO solution)

    setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); 
            // error SQL as object
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
        $db->exec("SET CHARACTER SET utf8");
    
    } catch (Exception $e) {
        echo ''.$e->getMessage().'
    '."\n"; } // default parameters $param = array(); $sql = "SELECT * FROM `cars` WHERE `id` != '' "; if(!empty($_POST['make'])){ $param[':make'] = $_POST['make']; $sql .= 'AND `make` = :make '; } if(!empty($_POST['model'])){ $param[':model'] = $_POST['model']; $sql .= 'AND `model` = :model '; } if(!empty($_POST['from'])){ $param[':from'] = $_POST['from']; $sql .= 'AND :from >= coalesce(`from`, 0) AND :from <= coalesce(`to`, 9999) '; } // we prepare our request $stmt = $db->prepare($sql); // we execute with our parameters $stmt->execute($param); while($r = $stmt->fetch()){ echo $r->id.' - '.$r->make.' - '.$r->model.' - '.$r->from; echo"
    "; }

    0 讨论(0)
提交回复
热议问题