Is it possible to do an active record query in CodeIgniter that will update an existing record if one already exists or insert if it doesnt, for the given k
If the replace solution suggested by Marcos Sánchez Urquiola in his answer does not work for you because you have an autoincrement column, the following is the cleanest way to do it while avoiding having to quote/sanitize the input yourself and letting Codeigniter do that.
$table = 'database.table'; // Usually you would have this in you model
$primary_key = 'id'; // You would also have this in you model
$data = [
'id' => '14',
'name' => 'John Smith',
'email' => 'john.smith@devnullmail.com',
];
// get keys and remove primary_key if it has been included in the data array
$updates_array = array_filter( array_keys($data), function($fieldName) use ($primary_key) { return $fieldName !== $primary_key; });
array_walk($updates_array, function(&$item){ $item = "{$item}=VALUES({$item})"; } );
$sql = $this->db->insert_string($table, $data) . ' ON DUPLICATE KEY UPDATE ' . implode(', ', $updates_array);
$this->db->query($sql);
/*
Generates an insert statement with the following at the end:
ON DUPLICATE KEY UPDATE
name=VALUES(name),
email=VALUES(email)
This way you work with the values you already supplied to $this->db->insert_string
*/