Skip to content

Instantly share code, notes, and snippets.

@MartkCz
Created May 11, 2017 11:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MartkCz/1f4166a87ec9f5ed97dd6572dc5bddcd to your computer and use it in GitHub Desktop.
Save MartkCz/1f4166a87ec9f5ed97dd6572dc5bddcd to your computer and use it in GitHub Desktop.
Doctrine multiple insert
<?php
declare(strict_types=1);
use Doctrine\DBAL\Connection;
class MultipleInsert {
/** @var Connection */
private $connection;
/** @var array */
private $inserts = [];
/** @var array */
private $values = [];
/** @var array */
private $types = [];
public function __construct(Connection $connection) {
$this->connection = $connection;
}
public function addInsert(string $tableName, array $data, array $types = []) {
if (empty($data)) {
$this->inserts[$tableName][] = [];
}
$this->inserts[$tableName][] = [
implode(', ', array_keys($data)),
implode(', ', array_fill(0, count($data), '?'))
];
foreach ($data as $key => $value) {
$this->values[] = $value;
$this->types[] = isset($types[$key]) ? $types[$key] : \PDO::PARAM_STR;
}
}
public function execute() {
$sql = '';
foreach ($this->inserts as $tableName => $records) {
foreach ($records as $array) {
if (!$array) {
$sql .= "INSERT INTO {$tableName} () VALUES();\n";
} else {
$sql .= "INSERT INTO {$tableName} ({$array[0]}) VALUES ({$array[1]});\n";
}
}
}
$this->connection->executeUpdate($sql, $this->values, $this->types);
$this->inserts = [];
$this->values = [];
$this->types = [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment