Skip to content

Instantly share code, notes, and snippets.

@tenebrousedge
Created April 13, 2013 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tenebrousedge/5380125 to your computer and use it in GitHub Desktop.
Save tenebrousedge/5380125 to your computer and use it in GitHub Desktop.
CakePHP Mysql Database driver extension for inserting lots of rows at once. Depending on how your data is being generated, this is liable to be extremely memory-inefficient.
//Store it in App/Model/Datasource/Database/MultiMysql.php
<?php
App::uses('Mysql', 'Model/Datasource/Database');
class MultiMysql extends Mysql {
public function insertMulti($table, $fields, $values) {
$table = $this->fullTableName($table);
$holder = implode(',', array_fill(0, count($fields), '?'));
$fields = implode(', ', array_map(array(&$this, 'name'), $fields));
$pdoMap = array(
'integer' => PDO::PARAM_INT,
'float' => PDO::PARAM_STR,
'boolean' => PDO::PARAM_BOOL,
'string' => PDO::PARAM_STR,
'text' => PDO::PARAM_STR
);
$columnMap = array();
$holder = implode(',', array_fill(0, count($values), '(' . $holder . ')'));
$sql = "INSERT INTO {$table} ({$fields}) VALUES {$holder}";
$statement = $this->_connection->prepare($sql);
foreach ($values[key($values)] as $key => $val) {
$type = $this->introspectType($val);
$columnMap[$key] = $pdoMap[$type];
}
$i = 1;
foreach ($values as $value) {
foreach ($value as $col => $val) {
$statement->bindValue($i, $val, $columnMap[$col]);
$i += 1;
}
}
//no longer transactional, oh well
$result = $statement->execute();
$this->_result = $statement;
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment