How to duplicate a record in MySQL using PHP

PostMay 7th, 2007 | Comments (7)
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

Post a comment

Name
URL
Email
Comment