I have an insert query (active record style) used to insert the form fields into a MySQL table. I want to get the last auto-incremented id for the insert operation as the return value of my query but I have some problems with it.
Inside the controller:
function add_post(){
$post_data = array(
'id' => '',
'user_id' => '11330',
'content' => $this->input->post('poster_textarea'),
'date_time' => date("Y-m-d H:i:s"),
'status' => '1'
);
return $this->blog_model->add_post($post_data);
}
And inside model:
function add_post($post_data){
$this->db->trans_start();
$this->db->insert('posts',$post_data);
$this->db->trans_complete();
return $this->db->insert_id();
}
I get nothing as the return of the add_post in model
Try this
function add_post($post_data){
$this->db->insert('posts', $post_data);
$insert_id = $this->db->insert_id();
return $insert_id;
}
In case of multiple inserts you could use
$this->db->trans_start();
$this->db->trans_complete();
Unneeded use of transactions. @Crowlix's answer is more concise.
@Abraham what about concurrent inserts?
@ShekharJoshi afaik the insert_id() functions returns the id of the last insert performed by the db object you're using. This should handle concurrent inserts, shouldn't it? Please correct me if I'm wrong.
How does codeigniter know which rows were added by a particular object?
@ShekharJoshi It's not about objects, CI's insert_id() returns the last inserted id as per MySQL's last_insert_id(), which keeps the last inserted id in a per-connection basis. Because of this, transactions are not needed for last inserted id's.