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

Rez*_*eri 152 mysql codeigniter

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

内部模型:

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

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

Sud*_*udz 255

试试这个

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

   return  $insert_id;
}
Run Code Online (Sandbox Code Playgroud)

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

$this->db->trans_start();
$this->db->trans_complete();
Run Code Online (Sandbox Code Playgroud)

  • @ShekharJoshi afaik insert_id()函数返回您正在使用的db对象执行的最后一次插入的id.这应该处理并发插入,不应该吗?如果我错了,请纠正我. (3认同)
  • @ShekharJoshi这不是关于对象,CI的insert_id()根据MySQL的[last_insert_id()]返回最后插入的id(https://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_last -insert-id),它基于每个连接保留最后插入的id.因此,最后插入的id不需要事务. (2认同)

Cro*_*lix 62

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

function add_post($post_data) {
    $this->db->insert('posts',$post_data);
    return $this->db->insert_id();
}
Run Code Online (Sandbox Code Playgroud)

  • @mander我相信insert_id()返回被调用的db对象执行的最后一次插入的id.即使存在并发插入,这是否意味着它总是返回对应于此特定db对象的插入对应的id? (8认同)

Sim*_*son 29

$id = $this->db->insert_id();
Run Code Online (Sandbox Code Playgroud)


Md.*_*Mia 10

文档:

$这个 - > DB-> INSERT_ID()

执行数据库插入时的插入ID号.

因此,你可以使用这样的东西:

$lastid = $this->db->insert_id();
Run Code Online (Sandbox Code Playgroud)

  • 请不要只提供链接,但请尝试在此处总结解决方案 (3认同)

Tri*_*IER 5

使用mysqli PHP驱动程序,提交后无法获取insert_id。

真正的解决方案是这样的:

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

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

  if( $this->db->trans_status() === FALSE )
  {
    $this->db->trans_rollback();
    return( 0 );
  }
  else
  {
    $this->db->trans_commit();
    return( $item_id );
  }
}
Run Code Online (Sandbox Code Playgroud)

代码结构来源:https ://codeigniter.com/user_guide/database/transactions.html#running-transactions-manually