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. 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