Im trying insert multi values with pdo but I getting error,it looks like it takes the last value from the last column in bindParam
and puts it for all columns:
//Prepare query and execute it
public function prepareMultiInsert($table = null, $columns = array(), $values = array(), $execute = false){
$qr = "INSERT INTO `$table`(";
//Keys
foreach ($columns as $i => $column){
$qr .= "`$column`, ";
}
$qr = substr($qr, 0, strlen($qr)-2) . ") VALUES";
foreach($values as $i => $v){
$qr .= "(";
//Values
foreach ($v as $index => $value){
$qr .= ":{$columns[$index]}$i, ";
}
$qr = substr($qr, 0, strlen($qr)-2) . "), ";
}
$stmt = $this->conn->prepare(substr($qr, 0, strlen($qr)-2));
foreach($values as $i => $v){
//BindValues
foreach ($v as $index => $value){
$stmt->bindParam($columns[$index] . $i, $value);
}
}
if($execute) return $this->queryInsert($stmt, true);
else return $stmt;
}
//Execute
public function queryInsert($stmt = null, $withIdReturn = false){
if($withIdReturn){
if($stmt->execute()) return new returnDb(true, $this->conn->lastInsertId(), null, $stmt->queryString);
else return new returnDb(false, null, $this->getError($stmt), $stmt->queryString);
}else return new returnDb($stmt->execute(), null, $this->getError($stmt), $stmt->queryString);
}
When I execute it like this:
$db->prepareMultiInsert("teste", ['id', 'name', 'age'],
[['1', 'woton', '19'],
['2', 'anita', '45'],
['3', 'jose', '13']], true));
ReturnDb return it:
object(returnDb)#5 (5) {
["return"]=>
bool(false)
["result"]=>
NULL
["query"]=>
string(123) "INSERT INTO `teste`(`id`, `name`, `age`) VALUES(:id0, :name0, :age0), (:id1, :name1, :age1), (:id2, :name2, :age2)"
["error"]=>
string(38) "Duplicate entry '13' for key 'PRIMARY'"
["fullError"]=>
array(3) {
[0]=>
string(5) "23000"
[1]=>
int(1062)
[2]=>
string(38) "Duplicate entry '13' for key 'PRIMARY'"
}
}
In table I have it:
He is catching last age and put in all columns on bind. Can anyone help me find the reason for the problem?