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
Here is a method that I hope can accomplish the same
/**
* Used to insert new row if a duplicate entry is encounter it performs an update
* @param string $table table name as string
* @param array $data associative array of data and columns
* @return mixed
*/
private function updateOnExist($table, $data)
{
$columns = array();
$values = array();
$upd_values = array();
foreach ($data as $key => $val) {
$columns[] = $this->db->escape_identifiers($key);
$val = $this->db->escape($val);
$values[] = $val;
$upd_values[] = $key.'='.$val;
}
$sql = "INSERT INTO ". $this->db->dbprefix($table) ."(".implode(",", $columns).")values(".implode(', ', $values).")ON DUPLICATE KEY UPDATE".implode(",", $upd_values);
return $this->db->query($sql);
}
You could do it simpler:
$sql = $this->db->insert_string(table, $array) . ' ON DUPLICATE KEY UPDATE ' .
implode(', ', $array);
$this->db->query($sql);
Basically what you are looking for might be 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.
Example:
$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
));
Updated Milaza's answer - Simply done
$updt_str = '';
foreach ($array as $k => $v) {
$updt_str = $updt_str.' '.$k.' = '.$v.',';
}
$updt_str = substr_replace($updt_str,";", -1);
$this->db->query($this->db->insert_string('table_name', $array).' ON DUPLICATE KEY UPDATE '.$updt_str);
I doesn't know Codeigniter Active Record Class has this method or not check the codeigniter docs for the methods containing in active record class
But you can achive this throug extending core models of codigniter.
By using this way you can use this method for all the models which extends this model class.
Just place the MY_model.php
into application/core/ and write the following code.
Class MY_Model extends CI_Model
{
public function insert_update($data)
{
// code for checking existing record.
if(//existing record)
fire the update query
else
fire the insert query
return insert/update id;
}
}
after creating the above file You have to change the All your models parent class to the new Extended model i.e. MY_Model
class some_model extends MY_Model
NOTE: You have to select the primary key from results and put it into the where condition.
It's very critical so what I do when I get the data from the controller I just check it have the ID or not if Id is present then I fired the update query if not then I fired The Insert Query.
BEST OF LUCK
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
*/