How To Clone a Row in MySQL Using Codeigniter?

If you've ever needed to clone or duplicate a MySQL row or record with a unique ID field, here is a clean and simple Codeigniter function. It clones the field names and the row values and then insert datas into table with unique primary key.
function DuplicateMySQLRecord ($table, $primary_key_field, $primary_key_val) 
{
   /* generate the select query */
   $this->db->where($primary_key_field, $primary_key_val); 
   $query = $this->db->get($table);
  
    foreach ($query->result() as $row){   
       foreach($row as $key=>$val){        
          if($key != $primary_key_field){ 
          /* $this->db->set can be used instead of passing a data array directly to the insert or update functions */
          $this->db->set($key, $val);               
          }//endif              
       }//endforeach
    }//endforeach

    /* insert the new record into table*/
    return $this->db->insert($table); 
}


Comments

Post a Comment

Popular Posts