Skip to content

Instantly share code, notes, and snippets.

@jagroop
Created November 27, 2017 10:37
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 jagroop/25132aa80261dcfc1e9f91c1f5a8cbd9 to your computer and use it in GitHub Desktop.
Save jagroop/25132aa80261dcfc1e9f91c1f5a8cbd9 to your computer and use it in GitHub Desktop.
insert or update if duplicate (Bulk)
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