I’m currently working on a project and came across the need to decide between inserting or updating a record in a MySQL table using PHP. The first thing that came to mind was to do a select and do the insert if my key wasn’t there, otherwise, do the update.
That’s when I found the “on duplicate key update” for inserts. It basically does the if/else logic in one clean SQL sweep. This is how it works:
Now if you try to insert another record having uname either ‘vinny’ or ‘vinny2’, you’ll get the following error:
To avoid that, use the “on duplicate key update” syntax: