How to Duplicate a Record Based on id Column in CodeIgniter

Duplicating a record based on an id allows you to quickly make a copy of an existing record, and then make only necessary changes without having to enter all the data from scratch. This is especially useful in situations where the same data needs to be repeated multiple times in a database. Data duplication can save time and effort while ensuring accuracy and consistency in the data records.

Duplicating records in CodeIgniter is kind of easy thanks to the framework’s Query Builder Class. In your model, create a function that reads the record based on id and then clones it depending on the $count parameter.

function duplicate($id, $count) {
    $this->db->where('id', $id);
    $query = $this->db->get($table);
    foreach ($query->result() as $row){
        foreach($row as $key => $val){
            if($key != 'id'){                
                $this->db->set($key, $val);
            }
        }
    }        
    $result = array();
    for ($i=0; $i < $count; $i++) { 
        $result[] = $this->db->insert($table);
    }

    return $result;
}

$table should be the name of the model’s table.

Then you can use it in any controller.

//duplicate the record with id 5 10 times
$this->my_model->duplicate(5, 10);

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close