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