How to ignore a parameter in a prepared mysqli query in PHP?

后端 未结 1 1099
刺人心
刺人心 2020-12-04 00:46

I have a prepared mysqli query like this:

$query = $database->prepare(\"SELECT * FROM items WHERE inStock > ? AND size < ? AND name LIKE ?\");               


        
1条回答
  •  自闭症患者
    2020-12-04 00:58

    You can build up a list of the criteria and add into a list the bind values and types, here is a quick mock up which uses two of the fields you refer to...

    $data = [];
    $params = "";
    $where = [];
    if ( !empty($name)) {
        $data[] = $name;
        $params.="s";
        $where[] = "name like ?";
    }
    if ( !empty($size)) {
        $data[] = $size;
        $params.="i";
        $where[] = "size < ?";
    }
    $sql = "SELECT * FROM items";
    if ( count($where) > 0 ){
        $sql .= " where ". implode ( " and ", $where);
    }
    $query = $database->prepare($sql);
    $query->bind_param($params, ...$data);
    $query->execute();
    

    Notice that the bind_param() uses the ... to allow you to pass an array instead of the individual fields.

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