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