如何在笨活动记录插入查询后得到最后插入的id(how to get last insert id a

2019-09-02 06:20发布

我有用于插入表单字段到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的模型回归

Answer 1:

试试这个

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


Answer 2:

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

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


Answer 3:

$id = $this->db->insert_id();


Answer 4:

从文档 :

$这个 - > DB-> INSERT_ID()

执行数据库插入时的插入件ID号。

因此,你可以使用这样的事情:

$lastid = $this->db->insert_id();


Answer 5:

因为你已经开始在数据插入这样的交易中,首先检查该交易完成与否。 一旦你开始交易,应当提交或根据事务的状态回滚;

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

在上文中,我们已经承诺在成功交易的数据,即使你得到的时间戳



Answer 6:

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



文章来源: how to get last insert id after insert query in codeigniter active record