How to duplicate a record in MySQL using PHP

PostMay 7th, 2007 | Comments (15)
If you've ever needed to duplicate a MySQL record with a unique ID field, here is a quick-n-dirty PHP function:

function DuplicateMySQLRecord ($table, $id_field, $id) {
    // load the original record into an array
    $result = mysql_query("SELECT * FROM {$table} WHERE {$id_field}={$id}");
    $original_record = mysql_fetch_assoc($result);
    
    // insert the new record and get the new auto_increment id
    mysql_query("INSERT INTO {$table} (`{$id_field}`) VALUES (NULL)");
    $newid = mysql_insert_id();
    
    // generate the query to update the new record with the previous values
    $query = "UPDATE {$table} SET ";
    foreach ($original_record as $key => $value) {
        if ($key != $id_field) {
            $query .= '`'.$key.'` = "'.str_replace('"','\"',$value).'", ';
        }
    }
    $query = substr($query,0,strlen($query)-2); # lop off the extra trailing comma
    $query .= " WHERE {$id_field}={$newid}";
    mysql_query($query);
    
    // return the new id
    return $newid;
}

Comments

SteveMay 31, 2007
Thanks! Looking for exactly this.
proraraAug 1, 2007
great!!!~ many thanks
Ng Xuan MuiApr 13, 2008
great !!!

thks so much !
richardMay 4, 2008
lovely, thanks! saved me some time
Nikos KatsikanisMay 19, 2008
super little function
ruelJun 3, 2008
very nice codes. great!
NikkoNov 11, 2008
Wow super useful, I was looking for this, thanks for sharing! I'll be using it on http://www.downloadablesoundz.com
S. Bedon-RouanetFeb 6, 2009
Quick-n-dirty, yes. ;)
Here's a less dirty version, using the "INSERT INTO table1 (SELECT * FROM table2 WHERE condition)" syntax, which is far much simpler.
The trick is to get the column names and then set the ID field to NULL.
2 queries instead of 3.

Please note that I adapted your function very quickly, and there may be 1 or 2 errors in it, but you see the principle.

Also note that you SHOULD add error testing after each mysql_query() command.

function DuplicateMySQLRecord ($table, $key_field, $key_value) {
// Get the names of all fields/columns in the table
$query = 'SHOW COLUMNS FROM ' . $table . ';';
$results = mysql_query($query);

// Generate the duplication query with those fields except the key
$query = 'INSERT INTO ' . $table . ' (SELECT ';

while ($row = mysql_fetch_array($results)) {
if ($row[0] == $key_field) {
$query .= 'NULL, ';
} else {
$query .= $row[0] . ', ';
} // END IF
} // END WHILE

$query = substr($query, 0, strlen($query) - 2);
$query .= ' FROM ' . $table . ' WHERE ' . $key_field . ' = "' . $key_value . '")';
mysql_query($query);

// Return the new id
$new_id = mysql_insert_id();
return $new_id;
}
khaos119Apr 15, 2009
Thanks! I like when things go smoothly :-)
Tom ElliottSep 4, 2009
Perfect! I have a table with ~300 fields in it and I need to duplicate (most) of the entries... I would have almost spent a day doing "INSERT INTO table (field1, field1... field300).." so you save me a lot of time :)
TerranceDec 13, 2009
Thanks! They work perfect!!
Patrick MooreFeb 23, 2010
This is fantastic; exactly what I was looking for!

Just a few tweaks and it works great in my application.

Thanks a lot!
Larry AndersonFeb 23, 2010
Looks like it will do the trick. :-)
Larry AndersonFeb 23, 2010
in Bedon-Rouanet's code I see where there would be one too many commas in the select.... here is an adjustment for the code

... // Generate the duplication query with those fields except the key
$query = 'INSERT INTO ' . $table . ' (SELECT ';
$i = 0;
while ($row = mysql_fetch_array($results)) {
$query .= ($i++ > 0 ? ' ,' : '');

...then remove the commas from the strings in the $query building statements that follow...
cscsnnJun 20, 2010
thanks a lot , perfect

Post a comment

Name
URL
Email
Comment