首页 文章

如何在codeigniter活动记录中插入查询后获取最后一个插入ID

提问于
浏览
130

我有一个插入查询(活动记录样式)用于将表单字段插入MySQL表 . 我想获取插入操作的最后一个自动递增的id作为我的查询的返回值,但我有一些问题 .

控制器内部:

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

内部模型:

function add_post($post_data){
    $this->db->trans_start();
    $this->db->insert('posts',$post_data);
    $this->db->trans_complete();
    return $this->db->insert_id();
}

我没有得到任何东西作为模型中add_post的返回

5 回答

  • 213

    来自documentation

    $ this-> db-> insert_id()执行数据库插入时的插入ID号 .

    因此,您可以使用以下内容:

    $lastid = $this->db->insert_id();
    
  • 27
    $id = $this->db->insert_id();
    
  • 60

    你必须使用 $lastId = $this->db->insert_id();

  • 0

    试试这个

    function add_post($post_data){
       $this->db->insert('posts', $post_data);
       $insert_id = $this->db->insert_id();
    
       return  $insert_id;
    }
    

    如果有多个插入,您可以使用

    $this->db->trans_start();
    $this->db->trans_complete();
    
  • 7

    这里不需要交易,这应该足够了:

    function add_post($post_data) {
        $this->db->insert('posts',$post_data);
        return $this->db->insert_id();
    }
    

相关问题