Last active
August 29, 2015 14:03
-
-
Save newage/227d7c3fb8202e473a76 to your computer and use it in GitHub Desktop.
MySql INSERT ... ON DUPLICATE KEY UPDATE Syntax in 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
/** | |
* Use INSERT ... ON DUPLICATE KEY UPDATE Syntax | |
* @since mysql 5.1 | |
* @param array $insertData For insert array('field_name' => 'field_value') | |
* @param array $updateData For update array('field_name' => 'field_value_new') | |
* @return bool | |
*/ | |
public function insertOrUpdate(array $insertData, array $updateData) | |
{ | |
$sqlStringTemplate = 'INSERT INTO %s (%s) VALUES (%s) ON DUPLICATE KEY UPDATE %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 = []; | |
foreach ($insertData as $column => $value) { | |
$insertQuotedValue[] = $driver->formatParameterName($column); | |
$insertQuotedColumns[] = $platform->quoteIdentifier($column); | |
$parameterContainer->offsetSet($column, $value); | |
} | |
/* Preparation update data */ | |
$updateQuotedValue = []; | |
foreach ($updateData as $column => $value) { | |
$updateQuotedValue[] = $platform->quoteIdentifier($column) . '=' . $driver->formatParameterName('update_' . $column); | |
$parameterContainer->offsetSet('update_'.$column, $value); | |
} | |
/* Preparation sql query */ | |
$query = sprintf( | |
$sqlStringTemplate, | |
$tableName, | |
implode(',', $insertQuotedColumns), | |
implode(',', array_values($insertQuotedValue)), | |
implode(',', $updateQuotedValue) | |
); | |
$statementContainer->setSql($query); | |
return $statementContainer->execute(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment