Created
July 8, 2014 16:12
-
-
Save bastman/e06ca8a8ab7ac0369763 to your computer and use it in GitHub Desktop.
Quick n dirty template to generate simple sql query: INSERT INTO TABLE ON DUPLICATE KEY UPDATE ...
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
/** | |
* @param string $table | |
* @param array $rowInsert | |
* @param array $rowUpdate | |
* @return array | |
*/ | |
function createSqlInsertIntoTableOnDuplicateKeyUpdate($table, $rowInsert, $rowUpdate) | |
{ | |
$insertColumnTokens = array(); | |
$insertValueTokens = array(); | |
$updateTokens = array(); | |
$params = array(); | |
foreach($rowInsert as $column=>$value) { | |
$paramName ='INSERT_'.$column; | |
$params[$paramName] = $value; | |
$insertColumnTokens[] = $column; | |
$insertValueTokens[] = ':'.$paramName; | |
} | |
foreach($rowUpdate as $column=>$value) { | |
$paramName ='UPDATE_'.$column; | |
$params[$paramName] = $value; | |
$updateTokens[] = ''.$column.' = '.':'.$paramName; | |
} | |
$sqlInsert = '('.implode(', ',$insertColumnTokens).')' | |
.' VALUES( | |
'.implode(' , ', $insertValueTokens).' | |
)'; | |
$sqlUpdate = implode(' , ',$updateTokens); | |
$sql = 'INSERT INTO '.$table | |
.' ' . $sqlInsert.' ON DUPLICATE KEY UPDATE '.$sqlUpdate | |
; | |
$result = array( | |
'sql'=>$sql, | |
'sqlInsert'=>$sqlInsert, | |
'sqlUpdate'=>$sqlUpdate, | |
'params'=>$params, | |
); | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment