如何在codeigniter活动记录中插入查询后获取最后一个插入ID [英] how to get last insert id after insert query in codeigniter active record

查看:48
本文介绍了如何在codeigniter活动记录中插入查询后获取最后一个插入ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个插入查询(活动记录样式)用于将表单字段插入到 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();

这篇关于如何在codeigniter活动记录中插入查询后获取最后一个插入ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆