如何添加另一个条件pdo sql语句
问题描述:
我在互联网上发现这个和迄今为止好一个条件!但我怎么能在sql语句中添加2个或更多的条件?如何添加另一个条件pdo sql语句
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天现在,我试了一切。 PLZ帮助我,并提前感谢!
答
我找到了解决方案,但我不得不减少安全.. 我只改变了这一点!
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);
}
我只想把它与1'$ where'参数,但要一个多维数组。例如:[['field','operator','value'],['field','operator','value']]''。你必须改变方法。 – Daan
我不介意改变方法,我试图$ where = array(array(),array())和$ field = $其中[0] [0]等...但它没有工作 –
你看到95%的我的项目是这些方法!但我需要过滤一些结果与3我假设的条件。 –