PHP

UPSERT (INSERT ... ON DUPLICATE KEY UPDATE)

admin by @admin ADMIN
15m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A MySQL upsert helper: insert a row, or if a unique key collides, update the same row with the new values. Returns whether the row was inserted (true) or updated (false).
PHP
Raw
<?php
function upsert(PDO $db, string $table, array $row, array $updateCols): bool {
    $cols   = array_keys($row);
    $colSql = '`' . implode('`,`', $cols) . '`';
    $phSql  = implode(',', array_fill(0, count($cols), '?'));
    $updSql = implode(',', array_map(fn($c) => "`$c`=VALUES(`$c`)", $updateCols));

    $sql = "INSERT INTO `$table` ($colSql) VALUES ($phSql) ON DUPLICATE KEY UPDATE $updSql";
    $stmt = $db->prepare($sql);
    $stmt->execute(array_values($row));
    // MySQL: rowCount = 1 for insert, 2 for update, 0 for no-op
    return $stmt->rowCount() === 1;
}

upsert($db, 'page_views', ['url'=>'/about','views'=>1], ['views']);
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.