如何添加另一个条件pdo sql语句

时间:2016-04-14 14:15:53

标签: php mysql pdo statements

我在互联网上找到了这个,到目前为止一个条件非常好!!但是如何在sql语句中添加2个或更多条件?

public static function getInstance() {
    if(!isset(self::$_instance)) {
        self::$_instance = new DB();
    }
    return self::$_instance;
}

public function query($sql, $params = array()) {
    $this->_error = false;

    if($this->_query = $this->_pdo->prepare($sql)) {
        $x = 1;
        if(count($params)) {
            foreach($params as $param) {
                $this->_query->bindValue($x, $param);
                $x++;
            }
        }

        if($this->_query->execute()) {
            $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount();
        } else {
            $this->_error = true;
        }
    }

    return $this;
}

public function action($action, $table, $where = array()) {
    if(count($where) === 3) {
        $operators = array('=', '>', '<', '>=', '<=');

        $field = $where[0];
        $operator = $where[1];
        $value = $where[2];

        if(in_array($operator, $operators)) {
            $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";

            if(!$this->query($sql, array($value))->error()) {
                return $this;
            }
        }

    }

    return false;
}

public function get($table, $where) {
    return $this->action('SELECT *', $table, $where);
}

我正在考虑创建另一个这样的函数:

public function get($table, $where1, $where2) {
    return $this->action('SELECT *', $table, $where, $where2);
}

条件是$where$where2等......我怎么能这样做?我知道我应该创建新方法action2和query2来实现更改,但正如我说我现在尝试5天,我尝试了一切。请帮助我并提前致谢!!

1 个答案:

答案 0 :(得分:-1)

我找到了解决方案,但我不得不降低安全性.. 我只改变了这个!

public function action3($action, $table, $where = array()) {
    /*if(count($where) === 6 ) {*/
        $operators = array('=', '>', '<', '>=', '<=');
        $field1 = $where[0];
        $operator1 = $where[1];
        $value1 = $where[2];
        $field2 = $where[3];
        $operator2 = $where[4];
        $value2 = $where[5];

/*if(in_array($operator, $operators)) {*/ $sql = "{$action} FROM {$table} WHERE {$field1} {$operator1} {$value1} AND {$field2} {$operator2} {$value2}"; if(!$this->query($sql, array($value1, $value2))->error()) {

                return $this;
            }
     /*   }*/

   /* }*/

    return false;
}

public function get3($table, $where) {
    return $this->action3('SELECT *', $table, $where);
}