简体   繁体   中英

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

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.

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();
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM