How to duplicate a record based on id in CodeIgniter

Duplicating records in CodeIgniter is kind of easy thanks to the framework’s Query Builder Class.

In your model, create a function that read record based on id then clone it depends 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 controllers.

//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 *

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.