I'm trying to insert multiple rows using a single prepared statement, but I can't make it work.
I have created the following helper methods:
// generate "(?, ?, ?, ?), (?, ?, ?, ?)" from cols and values
// to be used in a prepared statement
public function placeholders ($values, $cols) {
$row = '('.implode(',', array_fill(0, count($cols), '?')).')';
$place_holders = array_fill(0, count($values)/count($cols), $row);
return implode(',', $place_holders);
}
// generate the "?" placeholders and make the PDO transaction
protected function insertInto ($table, array $cols, array $values) {
$query = 'INSERT INTO `'.$table.'` (`'.implode('`,`', $cols).'`) VALUES '.$this->placeholders($values, $cols);
return $this->makeTransaction($query, $values);
}
// prepare and execute a PDO transaction
protected function makeTransaction ($query, array $values=array()) {
$this->pdo->beginTransaction();
$q = $this->pdo->prepare($query);
$q->execute($values);
return $this->pdo->commit();
}
As for the call itself, here it is:
$this->insertInto('table', array('f_key', 'c2', 'c3'), $values);
I'm using the following $values array:
$values = array(1, 'a', 'b', 2, 'c', 'd', ...);
Now the data doesn't get into the table but at the same time I don't get any exception or error of any kind. I've tried var_dump
ing $this->pdo->errorInfo()
after the call but it contains no error either. Any idea?