2014-09-22 124 views
0

我想通过创建我自己的类来简化我的数据库函数。
其中一个功能是绑定的。之前的工作,但现在它做了一些奇怪的事情
的代码是:goind这个PDO绑定函数有什么问题?

protected function tInsert(&$connection, $table, $data, $replaceSpecials){ 
    $sql = $this->createSqlQuery($table, $data); 

    $stmt = $connection->prepare($sql); 

    /* THIS WORKS 
    $stmt->bindParam(":username", $data["username"]); 
    $stmt->bindParam(":pass_hash", $data["pass_hash"]); 
    $stmt->bindParam(":salt", $data["salt"]); 
    $stmt->bindParam(":email", $data["email"]); 
    $stmt->bindParam(":sex", $data["sex"]); 
    $stmt->bindParam(":birthday", $data["birthday"]); 
    $stmt->bindParam(":code", $data["code"]); 
    */ 

    // THIS DOESNT 
    $stmt = $this->bind($stmt, $data, $replaceSpecials); 

    $stmt->execute(); 
} 

private function bind($stmt, $data, $replaceSpecials){ 
    if ($replaceSpecials) 
     foreach($data as $k => $d){ 
      $d = str_replace("<", "&lt;", 
       str_replace(">", "&gt;", $d)); 
      $stmt->bindParam(":" . $k, $d); 
     } 

    else if (!$replaceSpecials) 
     foreach($data as $k => $d) 
      $stmt->bindParam(":" . $k, $d); 

    else return $this->bind($stmt, $data, false); 
    return $stmt; 
} 

我确信我正确格式化我的数据。
注释掉的部分工作,而当我尝试它与我的自定义绑定功能 它不起作用。
它以前的其他功能..
它也不是sql查询..我确定它在某处的绑定函数。

我的最后结果是每个列都填满了最后一个给定的参数。
(在这种情况下将是:代码)

例如,这个阵列是数据

array (size=7) 
    'salt' => string 'b3d7201e14' (length=10) 
    'username' => string 'mister x' (length=8) 
    'pass_hash' => string 'd930f9a672bd12c9cf94aff748ca5bd100139bd5bdc7fafbdbfc8ad4bd79ba3c' (length=64) 
    'email' => string '[email protected]' (length=23) 
    'sex' => string 'm' (length=1) 
    'birthday' => string '25-11-1992' (length=10) 
    'code' => string '1ad21a5596cb556' (length=15) 

生成的SQL查询:

INSERT INTO temp_users (salt, username, pass_hash, email, sex, birthday, code) 
VALUES(:salt, :username, :pass_hash, :email, :sex, :birthday, :code) 

回答

1

替换bindParam()bindValue()。 bindParam定义了一个用于执行查询的变量名称。所以,当你的循环结束时,所有的变量都绑定到$d,在查询的执行点上它具有最后一次迭代的值。

通过将其更改为bindValue(),您可以设置函数调用时保留的值$d

+0

奇怪的是,它与其他功能一起工作..只有这一个没有我所期望的。我感谢你的答案,它的工作! – 2014-09-22 11:44:30