PHP PDO only last value of array gets inserted using bindValue & bindParam

走远了吗. 提交于 2020-01-30 02:56:16

问题


When below code is executed, only the last value of the array charlie gets inserted in the table.

$this->array = $array; //Array ( [0] => alpha [1] => bravo [2] => charlie )

$query = "INSERT INTO test SET Name = :Name";
$sql = $this->conn->prepare($query);

foreach($this->array as $k => &$v) {
    $sql->bindValue(":Name" , $v , PDO::PARAM_STR);
}
$sql->execute();

Im getting the same result using bindParam as well.

Can someone help me point out what I'm missing.

I'm totally baffled.


回答1:


This is only executing the insert with the last value as it's the last value that is bound to the statement. Call execute in each iteration of the loop.

foreach($this->array as $k => &$v) {
    $sql->bindValue(":Name" , $v , PDO::PARAM_STR);
    $sql->execute();
}



回答2:


Here's how bindParam is intended to be used:

$this->array = $array; //Array ( [0] => alpha [1] => bravo [2] => charlie )

$query = "INSERT INTO test SET Name = :Name";
$sql = $this->conn->prepare($query);
$sql->bindParam(":Name" , $value , PDO::PARAM_STR);    
foreach($this->array as $value) {
     $sql->execute();
}

That is, you bind the named parameter to one of your variables so every time you execute the query the named parameter will obtain its value from the current variable value.

By contrast, if you use bindValue you need to re-bind each time you need to change the named parameter value:

$query = "INSERT INTO test SET Name = :Name";
$sql = $this->conn->prepare($query);
foreach($this->array as $v) {
     $sql->bindValue(":Name" , $v , PDO::PARAM_STR);    
     $sql->execute();
}

The advantage of bindParam is that there's less allocations and passing around going on.



来源:https://stackoverflow.com/questions/46792100/php-pdo-only-last-value-of-array-gets-inserted-using-bindvalue-bindparam

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!