簡體   English   中英

如果同時插入兩條記錄,如何獲取最后一個 id

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

我有一個查詢,我以這樣的方式編寫了一個程序,在數據庫中創建了一個條目,我得到了 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");

在這樣的程序中,當兩個條目完全同時創建時,第二個事務的 id 更新為第一條記錄。 如何避免這種情況。 請建議。

您需要使用事務,基本上是一個接一個地提交一個查詢。 事務允許您一次執行一組查詢,鎖定數據庫直到所有查詢都運行(或回滾,以防萬一)。

用戶 1

自動提交關閉

  1. 運行查詢 1(插入數據)
  2. 檢索 last_insert_id
  3. 使用 last_insert_id 運行查詢 2

犯罪

用戶 2

自動提交關閉

  1. 運行查詢 1(插入數據)
  2. 檢索 last_insert_id
  3. 使用 last_insert_id 運行查詢 2

犯罪

要在 codeigniter 中使用事務,請查看答案。 您可以在此處找到 PHP 文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM