在foreach循环中的PDO :: bindParam,所有的值都被设置为相同的? [英] PDO::bindParam in a foreach loop, all values are being set as the same?
本文介绍了在foreach循环中的PDO :: bindParam,所有的值都被设置为相同的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<$>我试图让一个函数重复数据库调用更容易一些,这个函数应该(理论上)允许我使用数组绑定参数。 ($ tblName,$ queryParams = false){
$ this-> queryObject = $ this-> con> prepare($ this-> queryString );
if($ queryParams){
foreach($ queryParams as $ key => $ value){
$ this-> queryObject-> bindParam($ key,$ value);
$ this-> queryResult = $ this-> queryObject-> execute();
print_r($ this-> queryResult);
}
然后我这样调用:
$ queryParams = array(':userName'=> $ _POST ['username'],':password'=> $ _POST ['password'] ,':salt'=> $ userUser-> salt,':userEmail'=> $ _ POST ['email']);
$ registrationDb-> query('tblUser',$ queryParams);
数据库连接正在工作,并且正在进行写操作,但所有值都正在设置为 $ _ POST ['email]
,我不能解释为什么会发生这种情况。
有更好的方法来做到这一点?
解决方案
bindValue
来代替:
$ this-> ; queryObject-> bindValue($ key,$ value);
I am trying to make life a little bit easier for repeated database calls with the a function which should (in theory) allow me to bind parameters using an array:
function query($tblName,$queryParams = false){
$this->queryObject = $this->con->prepare($this->queryString);
if($queryParams){
foreach ($queryParams as $key => $value) {
$this->queryObject->bindParam($key, $value);
}
}
$this->queryResult = $this->queryObject->execute();
print_r($this->queryResult);
}
Which I am then calling like so:
$queryParams = array(':userName' => $_POST['username'], ':password' => $_POST['password'], ':salt'=>$userUser->salt, ':userEmail'=>$_POST['email']);
$registrationDb->query('tblUser', $queryParams);
The database connection is working, and there is a write being made, however, all the values are being set to $_POST['email]
, and I can't puzzle out why this is happening.
Is there a better way to be doing this?
解决方案
bindParam
binds variable by reference, so you need bindValue
instead:
$this->queryObject->bindValue($key, $value);
这篇关于在foreach循环中的PDO :: bindParam,所有的值都被设置为相同的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文