2011-03-17 113 views
0

我想在PHP中创建一个方法,它将动态绑定参数到PDO查询语句。不幸的是,在我的代码下面,我只能绑定1个参数,因为添加更多参数将覆盖以前的参数。不过,有没有解决这个问题的好方法?PDO绑定参数与参数

我希望有人能帮忙。谢谢!

function executeQuery($query, $critArr = null) { 
    $rows = array(); 
     try { 
      $stmt=$this->pdo->prepare($query); 
      if (!empty($critArr)) { 
       foreach($critArr as $cKey=>$cValue) { 
        $stmt->bindParam($cKey, $cValue); //!! 
       } 
      } 
      $stmt->execute(); 

回答

0

你不需要那样做。该execute方法已经花费的参数的阵列:

function executeQuery($query, $critArr = null) { 
    $rows = array(); 
     try { 
      $stmt=$this->pdo->prepare($query); 
      $stmt->execute($critArr); 
      // ... 

原来的问题是,bindParam作品通过引用,并foreach简单地一遍又一遍地重复使用相同的变量,而不是在循环的底部消灭它们和(重新)在顶部创建它们。你一遍又一遍地重新绑定相同的变量。 (顺便说一句,这是该mysqli延伸部具有同样的问题,而它也缺乏便利已经通吃一个阵列execute方法。)

0

你的功能与由参考& $ cValue传递的foreach $ cValue改善。这应该可以解决你的问题。

function executeQuery($query, $critArr = null) { 

    $rows = array(); 
     try { 
      $stmt=$this->pdo->prepare($query); 
      if (!empty($critArr)) { 
       foreach($critArr as $cKey=>&$cValue) { 
        $stmt->bindParam($cKey, $cValue); //!! 
       } 
      } 
      $stmt->execute();