Created
July 8, 2014 09:00
-
-
Save newage/e7336d05747330b0524f to your computer and use it in GitHub Desktop.
MySql multi insert for ZF2
This file contains hidden or 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
/** | |
* Insert many rows as one query | |
* @param array $data Insert array(array('field_name' => 'field_value'), array('field_name' => 'field_value_new')) | |
* @return bool | |
*/ | |
public function multiInsert(array $data) | |
{ | |
$sqlStringTemplate = 'INSERT INTO %s (%s) VALUES %s'; | |
$adapter = $this->tableGateway->adapter; /* Get adapter from tableGateway */ | |
$driver = $adapter->getDriver(); | |
$platform = $adapter->getPlatform(); | |
$tableName = $platform->quoteIdentifier('table_name'); | |
$parameterContainer = new ParameterContainer(); | |
$statementContainer = $adapter->createStatement(); | |
$statementContainer->setParameterContainer($parameterContainer); | |
/* Preparation insert data */ | |
$insertQuotedValue = []; | |
$insertQuotedColumns = []; | |
$i = 0; | |
foreach ($data as $insertData) { | |
$fieldName = 'field' . ++$i . '_'; | |
$oneValueData = []; | |
$insertQuotedColumns = []; | |
foreach ($insertData as $column => $value) { | |
$oneValueData[] = $driver->formatParameterName($fieldName . $column); | |
$insertQuotedColumns[] = $platform->quoteIdentifier($column); | |
$parameterContainer->offsetSet($fieldName . $column, $value); | |
} | |
$insertQuotedValue[] = '(' . implode(',', $oneValueData) . ')'; | |
} | |
/* Preparation sql query */ | |
$query = sprintf( | |
$sqlStringTemplate, | |
$tableName, | |
implode(',', $insertQuotedColumns), | |
implode(',', array_values($insertQuotedValue)) | |
); | |
$statementContainer->setSql($query); | |
return $statementContainer->execute(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you so much! Very useful and helpful!