问题
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