2015-05-28 67 views
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; 
    } 

如果有人可以帮助我这个,我将非常感激。谢谢!

回答

0

有一些问题在这里,例如:

  1. $values在你的第一种方法是一个连接字符串。将其转换为数组将给您带有1个元素的数组,这不是您所需要的。你需要一个数组,其中所有的值都是分开的,比如$values[] = $value;而不是$values .= $value;
  2. 当您尝试添加ORAND语句的组合时,您会遇到问题,因为使用括号会造成很大差异。
  3. 您正在使用准备好的语句作为值,但没有检查列名以防止sql注入。你应该在那里使用白名单。
+0

谢谢你有什么建议,我怎么能写得更好?我一直在为此奋斗了几天,并尝试了很多事情,但似乎如果我有一件事情来处理其他事情,等等。 – theStudent

+0

此外,如果我将它添加为$ values [] = ..我得到错误说ARRAY从查询函数字符串 – theStudent

+0

@theStudent当你调用该方法时,你是否删除了'数组($ values)'的数组部分?如果你不这样做,你会得到一个多维数组... – jeroen