Created
April 13, 2013 21:19
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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