Created
November 27, 2017 10:37
-
-
Save jagroop/25132aa80261dcfc1e9f91c1f5a8cbd9 to your computer and use it in GitHub Desktop.
insert or update if duplicate (Bulk)
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
public static function insertOrUpdate($table, array $rows) | |
{ | |
$first = reset($rows); | |
$columns = implode(',', array_map(function($value) | |
{ | |
return "$value"; | |
}, array_keys($first))); | |
$values = implode(',', array_map(function($row) | |
{ | |
return '(' . implode(',', array_map(function($value) | |
{ | |
return '"' . str_replace('"', '""', $value) . '"'; | |
}, $row)) . ')'; | |
}, $rows)); | |
$updates = implode(',', array_map(function($value) | |
{ | |
return "$value = VALUES($value)"; | |
}, array_keys($first))); | |
$sql = "INSERT INTO {$table}({$columns}) VALUES {$values} ON DUPLICATE KEY UPDATE {$updates}"; | |
return mysql_query($sql); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment