首頁 > 資料庫 > mysql教程 > 如何使用 CodeIgniter 的 Active Record 檢索上次插入 ID?

如何使用 CodeIgniter 的 Active Record 檢索上次插入 ID?

Barbara Streisand
發布: 2024-11-04 22:24:02
原創
373 人瀏覽過

How to Retrieve the Last Insert ID using CodeIgniter's Active Record?

使用CodeIgniter 的Active Record 檢索上次插入ID

使用CodeIgniter 的Active Record 執行插入查詢時,通常需要檢索插入的查詢時,通常需要檢索插入的ID。指派給新插入行的遞增 ID。但是,在取得此 ID 時遇到問題可能會令人沮喪。

解:

在模型的插入方法中,使用以下步驟:

<code class="php">function add_post($post_data) {
    $this->db->insert('posts', $post_data);
    $insert_id = $this->db->insert_id();

    return $insert_id;
}</code>
登入後複製

insert_id() 函數檢索最後插入的行的ID。

如果您在單一交易中執行多個插入,則需要將插入包含在交易區塊中:

<code class="php">$this->db->trans_start();
$this->db->insert('posts', $post_data);
$insert_id = $this->db->insert_id();
$this->db->trans_complete();</code>
登入後複製

按照以下步驟,您可以使用CodeIgniter 的Active Record 成功檢索插入操作後的最後一個插入ID,確保準確識別新插入的記錄。

以上是如何使用 CodeIgniter 的 Active Record 檢索上次插入 ID?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板