MySQL. How to insert a row or update if exists in MySQL.

Posted by Stanislav Furman  on February 25, 2013

Being a web developer, I personally like short solutions, and when I code, I try to write as less code as possible. At the same time the code has to be readable for other developers without using comments.

If you want to combine create/update function into one, MySQL offers you a very useful statement : INSERT ... ON DUPLICATE KEY UPDATE.

Example:


INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6) ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);

This statement can be easily used in your function that creates a new entry or updates an existing one if the key exists in the table.


<?php
function saveUserInfo($id, $name, $email, $phone) {
	$sql = "INSERT INTO table (`id`,`name`,`email`,`phone`) 
		VALUES ('{$id}','{$name}','{$email}','{$phone}') 
			ON DUPLICATE KEY UPDATE name='{$name}',email='{$email}',phone='{$phone}'";
	
	// ... execute SQL query here
}
?>

So, now if $id variable is empty (new row), the function will create a new row in the DB. If the $id is set and exists in the table, the query will update the row.

Voila! Enjoy your short and clean code.


Leave your comment

Fields with * are required.

* When you submit a comment, you agree with Terms and Conditions of Use.