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

后端 未结 9 922
庸人自扰
庸人自扰 2020-11-28 01:59

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 re

相关标签:
9条回答
  • 2020-11-28 02:29

    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();
    
    0 讨论(0)
  • 2020-11-28 02:29

    Using the mysqli PHP driver, you can't get the insert_id after you commit.

    The real solution is this:

    function add_post($post_data){
      $this->db->trans_begin();
      $this->db->insert('posts',$post_data);
    
      $item_id = $this->db->insert_id();
    
      if( $this->db->trans_status() === FALSE )
      {
        $this->db->trans_rollback();
        return( 0 );
      }
      else
      {
        $this->db->trans_commit();
        return( $item_id );
      }
    }
    

    Source for code structure: https://codeigniter.com/user_guide/database/transactions.html#running-transactions-manually

    0 讨论(0)
  • 2020-11-28 02:42

    because you have initiated the Transaction over the data insertion so, The first check the transaction completed or not. once you start the transaction, it should be committed or rollback according to the status of the transaction;

    function add_post($post_data){
      $this->db->trans_begin() 
      $this->db->insert('posts',$post_data);
      $this->db->trans_complete();
      if ($this->db->trans_status() === FALSE){
        $this->db->trans_rollback();
        return 0;
      }else{
        $this->db->trans_commit();
        return $this->db->insert_id();
      }
    }``
    

    in the above, we have committed the data on the successful transaction even you get the timestamp

    0 讨论(0)
提交回复
热议问题