If you've ever built an application that interacts with a database and allows users to edit data, or one that migrates data from one system to another you've probably written code like this:
// $id would have been set based on some other operation above.// I'm setting it here for clarity.$id = 1;
$result = mysql_query("SELECT id FROM table_name WHERE id = $id");
if(mysql_num_rows() == 0){
// Zero results, the record doesn't exist, add it.mysql_query("INSERT INTO table_name (id,a,b) VALUES ($id,2,3)");
}else{
// The record exists, update it.mysql_query("UPDATE table_name SET a = 1, b = 2 WHERE id = $id");
}Well, thanks to the ON DUPLICATE KEY UPDATE option in MySQL this can be condensed to the following:
$result = mysql_query("INSERT INTO table_name SET id = $id, a = 2, b = 3
ON DUPLICATE KEY UPDATEa = 2, c = 3");