使用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中文網其他相關文章!