Skip to main content

How to Duplicate a Record Based on Id in CodeIgniter

In CodeIgniter, there are times when you need to duplicate a record in the database. For example, you may have a customer orders table and need to create a new order for the same customer. In this case, you would want to duplicate the customer’s information in the orders table.

To do this, you can create a CodeIgniter duplication function. This function will take the id of the original record with a counter and create a new record with the same information. You can then update the new record with the appropriate information for the new order. Duplicating records in this way can save you time and ensure that your data is accurate.

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;
}

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