MySql // Add Duplicate Record with new ID

MySql // Add Duplicate Record with new ID

 
Needed a cool little function like this, found it here:

http://bit.ly/2ortNmg

Updated it for mysqli and added some error checking:

function DuplicateMySQLRecord ($mysqliD, $table, $id_field, $id) {
    // load the original record into an array
    if(!$result = $mysqliD->query("SELECT * FROM {$table} WHERE {$id_field}={$id}")) {
		die('There was an error getting original record [' . $mysqliD->error . ']');
	};
	
    $original_record = $result->fetch_assoc() ;
    
    // insert the new record and get the new auto_increment id
    if(!$result=$mysqliD->query("INSERT INTO {$table} (`{$id_field}`) VALUES (NULL)")){
		die('There was an error running the dummy insert [' . $mysqliD->error . ']');
	}
	
    $newid = $mysqliD->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}";
    
	if(!$result=$mysqliD->query($query)) {
		die('There was an error populating the new record [' . $mysqliD->error . ']');
	}
    
    // return the new id
    return $newid;
}