how to get last insert id after insert query in codeigniter active record

0 votes

I have an active record style insert query which has been 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 have been facing issues with it. Have shared my code below:-

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); 
}


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 the model. Could anyone please help me with this? 

Feb 23 in Others by Rahul
• 8,980 points
249 views

1 answer to this question.

0 votes

To answer your doubt, try the following lines of code:-

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();

answered Feb 23 by Aditya
• 7,280 points

Related Questions In Others

0 votes
2 answers

How to get the URL of the current tab in Google Chrome?

Its so simple.... If you want to ...READ MORE

answered Aug 12, 2020 in Others by Steve
• 200 points
719 views
0 votes
0 answers

To query Last 7 days data in DynamoDB

HashKey(Date) ,RangeKey(timestamp) This is what my dynamo DB ...READ MORE

Apr 9 in Others by Kichu
• 19,040 points
131 views
0 votes
0 answers

How to get response from S3 getObject in Node.js?

I am attempting to get data back ...READ MORE

Apr 23 in Others by Kichu
• 19,040 points
188 views
0 votes
1 answer
0 votes
0 answers
0 votes
1 answer

Want a command to be executed in Salt only if a directory is empty

You should consider using this inside your ...READ MORE

answered Jun 12, 2018 in DevOps Tools by Damon Salvatore
• 5,980 points
649 views
0 votes
1 answer

How to get current time and date in Android

In order to get the current date ...READ MORE

answered Feb 23 in Others by Aditya
• 7,280 points
190 views
0 votes
1 answer

How do I get the current date and time in PHP?

The time would go by your server ...READ MORE

answered Feb 16 in Others by Aditya
• 7,280 points
27 views
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP