[英]Invalid number of parameters binding PDO
我正在為該項目使用教程,但是我嘗試擴展資料中提供的內容。 我正在嘗試使用一個函數,該函數在綁定值以創建具有3個以上WHERE值的查詢之前就創建查詢。
這是代碼:
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;
}
嵌套的其他IF語句讀取count($ where)=== 3的部分工作正常,但是第一個嵌套的IF'count($ where> 3)`拋出錯誤。
我試圖找到一種正確設置此方法的方法,以便可以使用不止3個where值。
這也是我的查詢資料夾:
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;
}
如果有人可以幫助我解決這個問題,我將非常感謝...謝謝!
這里有一些問題,例如:
$values
是連接的字符串。 將其轉換為數組將為您提供一個包含1個元素的數組,這不是您所需要的。 您將需要一個所有值都分開的數組,例如$values[] = $value;
而不是$values .= $value;
。 OR
和AND
語句的組合時,您會遇到問題,因為使用括號進行分組會產生很大的不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.