简体   繁体   English

如果同时插入两条记录,如何获取最后一个 id

[英]how to get last id if two record inserted at same time

I have a query, i have written a program in such a way an entry created in database and i am getting last_id, used this last id to update in second table.我有一个查询,我以这样的方式编写了一个程序,在数据库中创建了一个条目,我得到了 last_id,使用这个最后一个 id 在第二个表中更新。

$table='user';
$data = array('array having user data');
$this->db->insert($table, $data);
$last_id = $this->db->insert_id();

$this->db->where('user_id', $last_id);
$this->db->set('wallet_total_amount', "wallet_total_amount");

In such program when two entries created at exactly same time then the id of second transaction updated with first record.在这样的程序中,当两个条目完全同时创建时,第二个事务的 id 更新为第一条记录。 how to avoid this.如何避免这种情况。 please suggest.请建议。

You need to use transactions, basically committing one query after the other.您需要使用事务,基本上是一个接一个地提交一个查询。 Transactions allow you to perform one set of queries at a time, locking the database until all the queries are run (or rolled back, in case of errors).事务允许您一次执行一组查询,锁定数据库直到所有查询都运行(或回滚,以防万一)。

User 1用户 1

auto commit off自动提交关闭

  1. Run query 1 (Insert data)运行查询 1(插入数据)
  2. Retrieve last_insert_id检索 last_insert_id
  3. Run query 2 using last_insert_id使用 last_insert_id 运行查询 2

commit犯罪

User 2用户 2

auto commit off自动提交关闭

  1. Run query 1 (Insert data)运行查询 1(插入数据)
  2. Retrieve last_insert_id检索 last_insert_id
  3. Run query 2 using last_insert_id使用 last_insert_id 运行查询 2

commit犯罪

To use transactions in codeigniter, have a look to this answer.要在 codeigniter 中使用事务,请查看答案。 Here you can find the PHP documentation.您可以在此处找到 PHP 文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM