In order to use ON DUPLICATE KEY UPDATE
you must create an index to enforce uniqueness across the two columns id2, name
for MySQL to be able to detect duplication. This will create the index with an identifier called idx_uniq_id2_name
`
Before you attempt this, you must ensure that you do not already have more than one occurrence of the combination of id2, name
anywhere in your table. You can verify that with:
-- Check for non-unique rows
SELECT id2, name FROM table GROUP BY id2, name HAVING COUNT(*) > 1
If that returns no rows, you can successfully create the multi-column index.
-- Create a multi-column unique index
ALTER TABLE `table` ADD UNIQUE INDEX `idx_uniq_id2_name` (`id2`, `name`);
After the index has been created, you must correct the syntax of your INSERT
statement such that it has no WHERE
clause (which is never allowed for an INSERT
).
INSERT INTO `table`
(id2, name, city)
VALUES ('$id2', '$name', '$new_city')
ON DUPLICATE KEY UPDATE city = '$new_city';
Please be advised that your use of variables like $new_city
in the SQL statement suggest you are not using prepare()/execute()
with PDO or MySQLi in your code. I would recommend reviewing How can I prevent SQL injection in PHP for suggestions on how to improve the situation.