Insert or update in one query (upsert)
ON DUPLICATE KEY UPDATE inserts a new row or updates the existing one. Needs a UNIQUE key.
PHP · Insert or update in one query (upsert)Advanced
$sql = 'INSERT INTO users (name, email, hits) VALUES (:name, :email, 1)
ON DUPLICATE KEY UPDATE name = VALUES(name), hits = hits + 1';
$st = $pdo->prepare($sql);
$st->execute([':name' => 'Ali', ':email' => 'ali@x.com']); // existing email: updates
$st->execute([':name' => 'New', ':email' => 'new@x.com']); // new email: inserts
// rowCount(): 1 = inserted, 2 = updated, 0 = nothing changedmysqlupserton-duplicate