CodeIgniter activerecord,如何检索最后插入的ID?

154

在CodeIgniter中,有没有任何选项可以获取新记录的最后插入ID?

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

假设数据表包含id(自增)、firstcolumn和secondcolumn字段。

这样,您就可以在以下代码中使用插入的id。


4
我多次来到这个问题。非常感谢! - giripp
11个回答

0
在CodeIgniter 3中,您可以按照以下方式完成:
if($this->db->insert("table_name",$table_data)) {
    $inserted_id = $this->db->insert_id();
    return $inserted_id;
}

你可以从这里https://codeigniter.com/user_guide/database/helpers.html获取Codeigniter 3的帮助。

在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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接