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

2021-11-20 00:00:00 mysql codeigniter

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

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.

控制器内部:

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 的返回我什么也没得到

I get nothing as the return of the add_post in model

推荐答案

试试这个

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

相关文章