1
我正在使用该项目的教程,但是我正在尝试扩展材料中提供的内容。我正在尝试使用一个函数,它在绑定值之前创建查询,以创建具有多于3个WHERE值的查询。绑定PDO的参数数量无效
下面是代码:
private function action($action, $table, $where = array()){
$operators = array('=', '>', '<', '>=', '<=' , 'AND' ,'OR', 'LIKE', 'GROUP BY','ORDER BY', 'ASC', 'DESC');
if(!empty($where)){
$sql = "{$action} FROM {$table} WHERE ";
if(count($where) > 3){
$isVal = FALSE;
$values = '';
foreach ($where as $value) {
switch(trim($value)){
case '=':
case '>':
case '<':
case '>=':
case '<=':
$sql .= "{$value}";
$isVal = true;
break;
default:
if($isVal){
$sql .= " ? ";
$values .= $value;
$isVal = false;
}else{
$sql .= "{$value}";
}
break;
}
}
if(!$this->query($sql, $values)->error()){return $this;}
/////////////////////////////////////////
// From this point down everything works!!!
////////////////////////////////////////////
}else if(count($where) === 3){
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)){
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?"; // NO $value ?
if(!$this->query($sql, array($value))->error()){return $this;}
}
}
}else{
// If array is empty
$sql = "{$action} FROM {$table}";
if(!$this->query($sql)->error()){return $this;}
}
return FALSE;
}
部分,其中嵌套else if语句可读取计数($哪里)=== 3个工作正常,但第一个嵌套的IF“计数($其中> 3)`抛出我错了。
我想找到一种方法来正确设置它,这样我就可以使用多于3的值。
而且,这里是我的查询绑定:
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++;
}
}// End IF count
if($this->_query->execute()){
$this->_lastID = $this->_pdo->lastInsertId();
try{
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
}catch(Exception $e){
// Catch Error
}
$this->_count = $this->_query->rowCount();
}else{
$this->_error = TRUE;}
}
return $this;
}
如果有人可以帮助我这个,我将非常感激。谢谢!
谢谢你有什么建议,我怎么能写得更好?我一直在为此奋斗了几天,并尝试了很多事情,但似乎如果我有一件事情来处理其他事情,等等。 – theStudent
此外,如果我将它添加为$ values [] = ..我得到错误说ARRAY从查询函数字符串 – theStudent
@theStudent当你调用该方法时,你是否删除了'数组($ values)'的数组部分?如果你不这样做,你会得到一个多维数组... – jeroen