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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16440366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 17:33:50  来源:igfitidea点击:

how to get last insert id after insert query in codeigniter active record

mysqlcodeigniter

提问by Afghan Dev

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.

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

Inside the controller:

控制器内部:

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

And inside model:

和内部模型:

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

I get nothing as the return of the add_post in model

作为模型中 add_post 的返回,我一无所获

回答by Sudz

Try this

尝试这个

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

回答by Crowlix

A transaction isn't needed here, this should suffice:

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

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

回答by Simon Carlson

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

回答by Md.Jewel Mia

From the documentation:

文档

$this->db->insert_id()

The insert ID number when performing database inserts.

$this->db->insert_id()

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

Therefore, you could use something like this:

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

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

回答by KISHOR PANT

because you have initiated the Transaction over the data insertion so, The first check the transaction completed or not. once you start the transaction, it should be committed or rollback according to the status of the transaction;

因为你已经发起了Transaction 过数据插入所以,首先检查事务完成与否。一旦开始事务,就应该根据事务的状态提交或回滚;

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

in the above, we have committed the data on the successful transaction even you get the timestamp

在上面,即使您获得时间戳,我们也已提交有关成功交易的数据

回答by Fabus

Just to complete this topic: If you set up your table with primary key and auto increment you can omit the process of manually incrementing the id.

只是为了完成本主题:如果您使用主键和自动递增设置表,则可以省略手动递增 id 的过程。

Check out this example

看看这个例子

if (!$CI->db->table_exists(db_prefix() . 'my_table_name')) {
    $CI->db->query('CREATE TABLE `' . db_prefix() . "my_table_name` (
  `serviceid` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(64) NOT NULL,
  `hash` varchar(32) NOT NULL,
  `url` varchar(120) NOT NULL,
  `datecreated` datetime NOT NULL,
  `active` tinyint(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=" . $CI->db->char_set . ';');

Now you can insert rows

现在您可以插入行

$this->db->insert(db_prefix(). 'my_table_name', [
            'name'         => $data['name'],
            'hash'            => app_generate_hash(),
            'url'     => $data['url'],
            'datecreated'     => date('Y-m-d H:i:s'),
            'active'          => $data['active']
        ]);

回答by nitol arafat

**Inside Model**
function add_info($data){
   $this->db->insert('tbl_user_info',$data);
   $last_id = $this->db->insert_id();
   return  $last_id;
}

**Inside Controller**
public function save_user_record() {
  $insertId =  $this->welcome_model->save_user_info($data);
  echo $insertId->id;
}

回答by Tristan CHARBONNIER

Using the mysqli PHP driver, you can't get the insert_id after you commit.

使用mysqli PHP驱动,提交后获取不到insert_id。

The real solution is this:

真正的解决办法是这样的:

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

Source for code structure: https://codeigniter.com/user_guide/database/transactions.html#running-transactions-manually

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

回答by Pawan Kr

You must use $lastId = $this->db->insert_id();

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