CodeIgniter update() defaults to insert() CodeIgniter update() defaults to insert() codeigniter codeigniter

CodeIgniter update() defaults to insert()


I found a good solution in this link, I hope it helps if anyone is still looking for a solution in codeigniter:

$sql = 'INSERT INTO menu_sub (id, name, desc, misc)        VALUES (?, ?, ?, ?)        ON DUPLICATE KEY UPDATE             name=VALUES(name),             desc=VALUES(desc),             misc=VALUES(misc)';$query = $this->db->query($sql, array( $id,                                        $this->validation->name,                                        $this->validation->desc,                                        $this->validation->misc                                      ));  


Perhaps what you are looking for is this INSERT ... ON DUPLICATE KEY UPDATE - provided that you are using MySQL and your id is a unique key on the table.

You'd have to manually construct the query and pass to the $this->db->query() function instead of any built in active record like helper functions of the DB Driver.


I don't why would you use this, but one way to handle this (with one function as you requested) is the following:

function update_or_insert($data){    if(!array_key_exists('id',$data))        return $this->db->insert($data);    $row = $this->db->get_where('mytable',['id' => $data['id']])->row();    if(!$row) return false;    $this->db->where($row->id);    return $this->db->update('my_table',$data); }

$data can be a whole $_POST array passed from the controller. I would place this function inside the model that represents the table (my_table).

This is one solution that should work. Let us know.