[eluser]JoostV[/eluser]
Code:
if($this->ID == -1){
unset $this->ID;
}
$this->db->insert(‘table’, $this);
$this->ID = $this->db->insert_id();
It is even handier to create a generic save() function in your model. That way, you do not have to worry about whether you are dealing with an insert or an update. You just save something and the function always returns the save ID.
I use this in my base model, that is subclassed by all my other models.
Code:
// Set these vars in the model that subclasses this MY_Model
var $table = 'my_table'; // The table name
var $primary_field = 'id'; // The name of the primary key field
/**
* Insert or update a record
*
* @param Array $data The data to be updated or inserted
* @param Integer $id The record id (optional)
* @return Mixed The id of the updated or inserted record, or false on failure
*/
function save($data, $id){
// Sanitize id. We always use (int) auto_increment as primary key.
$id = (int) $id;
// Insert or update record
if($id > 0){
// we have an id, this is an update
$this->db->where($this->primary_field, $id);
$this->db->update($this->table, $data);
}
else {
// we have no id, this is an insert
$this->db->insert($this->table, $data);
$id = $this->db->insert_id();
}
// Return id on succes, false on failure
return $this->db->affected_rows() > 0 ? $id : false;
}