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

后端 未结 9 921
庸人自扰
庸人自扰 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:17

    From the documentation:

    $this->db->insert_id()

    The insert ID number when performing database inserts.

    Therefore, you could use something like this:

    $lastid = $this->db->insert_id();
    
    0 讨论(0)
  • 2020-11-28 02:20
    **Inside Model**
    function add_info($data){
       $this->db->insert('tbl_user_info',$data);
       $last_id = $this->db->insert_id();
       return  $last_id;
    }
    
    **Inside Controller**
    public function save_user_record() {
      $insertId =  $this->welcome_model->save_user_info($data);
      echo $insertId->id;
    }
    
    0 讨论(0)
  • 2020-11-28 02:21

    Just to complete this topic: If you set up your table with primary key and auto increment you can omit the process of manually incrementing the id.

    Check out this example

    if (!$CI->db->table_exists(db_prefix() . 'my_table_name')) {
        $CI->db->query('CREATE TABLE `' . db_prefix() . "my_table_name` (
      `serviceid` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
      `name` varchar(64) NOT NULL,
      `hash` varchar(32) NOT NULL,
      `url` varchar(120) NOT NULL,
      `datecreated` datetime NOT NULL,
      `active` tinyint(1) NOT NULL DEFAULT '1'
    ) ENGINE=InnoDB DEFAULT CHARSET=" . $CI->db->char_set . ';');
    

    Now you can insert rows

    $this->db->insert(db_prefix(). 'my_table_name', [
                'name'         => $data['name'],
                'hash'            => app_generate_hash(),
                'url'     => $data['url'],
                'datecreated'     => date('Y-m-d H:i:s'),
                'active'          => $data['active']
            ]);
    
    0 讨论(0)
  • 2020-11-28 02:23
    $id = $this->db->insert_id();
    
    0 讨论(0)
  • 2020-11-28 02:25

    You must use $lastId = $this->db->insert_id();

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

    A transaction isn't needed here, this should suffice:

    function add_post($post_data) {
        $this->db->insert('posts',$post_data);
        return $this->db->insert_id();
    }
    
    0 讨论(0)
提交回复
热议问题