簡體   English   中英

CodeIgniter activerecord,檢索最后插入的ID?

[英]CodeIgniter activerecord, retrieve last insert id?

是否有任何選項可以在 CodeIgniter 中獲取新記錄的最后一個插入 ID?

$last_id = $this->db->insert('tablename',
    array('firstcolumn' => 'value',
    'secondcolumn' => 'value')
);

考慮到字段 id(自動增量)firstcolumn 和 secondcolumn 的表構成。

這樣您就可以在以下代碼中使用插入 ID。

羡慕我...

我查看了用戶指南,第一個函數是$this->db->insert_id();

這也適用於活動記錄插入...

編輯:我更新了鏈接

最后插入 id 意味着您可以通過在活動記錄中使用此方法來獲取插入的自動增量 id,

$this->db->insert_id() 
// it can be return insert id it is 
// similar to the mysql_insert_id in core PHP

你可以參考這個鏈接,你可以找到更多的東西。

執行查詢的信息

對於特定表,您不能使用 $this->db->insert_id() 。 即使最后一次插入發生在很久以前,也可以像這樣獲取。 可能是錯誤的。 但對我來說效果很好

     $this->db->select_max('{primary key}');
     $result= $this->db->get('{table}')->row_array();
     echo $result['{primary key}'];

有助於請求 id 和查詢的詳細信息列表是

獲取上次插入的 ID:這將從表中獲取最后一條記錄

$this->db->insert_id(); 

獲取 SQL 查詢在模態請求后添加此項

$this->db->last_query()

在插入查詢后,使用此命令$this->db->insert_id(); 返回最后插入的 id。

例如:

$this->db->insert('Your_tablename', $your_data);

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

echo $last_id // assume that the last id from the table is 1, after the insert query this value will be 2.

試試這個。

public function insert_data_function($your_data)
{
    $this->db->insert("your_table",$your_data);
    $last_id = $this->db->insert_id();
    return $last_id;
}

$this->db->insert_id();

試試這個作為你想要的問題。

$this->db->insert_id();

執行數據庫插入時返回插入 ID 號

codeigniter-3 的查詢輔助方法

$this->db->insert_id()  

//請試試這個

if($this->db->insert('Your_tablename', $your_data)) {
    return $this->db->insert_id();
}
return false 

在 codeigniter 3 中,您可以按如下方式進行:

if($this->db->insert("table_name",$table_data)) {
    $inserted_id = $this->db->insert_id();
    return $inserted_id;
}

您可以從這里獲得有關 Codeigniter 3 的幫助https://codeigniter.com/user_guide/database/helpers.html

在 Codeigniter 4 中,您可以獲得最后插入的 ID,如下所示:

$builder = $db->table("your table name");
if($builder->insert($table_data)) {
    $inserted_id = $db->insertID();
    return $inserted_id;
}

您可以從這里獲得有關 Codeigniter 4 的幫助https://codeigniter4.github.io/userguide/database/helpers.html

暫無
暫無

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

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