I came across a situation where I needed to pull records from 1 db to another on a recurring basis. I read many different ways to do it via searching around the net. Some of the suggestions included creating a temporary table and copying it over. What was lacking was that sometimes the new table also needed to be UPDATED, as the information changed from the original table.
I’ve come up with a dirty little example to show this can be done. There are more keywords that can enhance the ON DUPLICATE KEY UPDATE function even more. The Example is assuming an “employees” table that looks like so:
| employees |
|---|
| id (PK) |
| first_name |
For brevity, I’ve left out connection data etc;
$myArray = array(0 => array('id' => '1', 'fname' => 'Steve'), array('id' => '2', 'fname' => 'sara'), array('id' => '3', 'fname' => 'Matt') ); // Don't forget to validate & clean your data // Connect to db here foreach($myArray as $key => $value){ $query = "INSERT INTO employees (id, first_name) VALUES ('$value[id]', '$value[fname]') ON DUPLICATE KEY UPDATE first_name = '$value[fname]'"; $result = mysql_query($query); if(!$result){ print("Problem: " . mysql_error() . ""); } else { print("Success !"); } }
Read the manual on this for more information. This snippet will INSERT if a UNIQUE (in this case ‘id’) does not exist. It will UPDATE any existing unique. In this case any existing ‘id’s, the ‘first_name’ column will get updated.
One could also use the REPLACE function. As I understand the difference, REPLACE will DELETE any matching uniques, and INSERT a new record in it’s place.
Comments? Better ways? I’m always up for learning something new so please chime in ![]()

