CodeIgniter activerecord,检索最后一个插入ID?

时间:2009-12-31 16:11:41

标签: php codeigniter

是否有任何选项可以在CodeIgniter中获取新记录的最后一个插入ID?

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

考虑表格的字段id(autoincrement)firstcolumn和secondcolumn。

这样您可以在以下代码中使用插入ID。

11 个答案:

答案 0 :(得分:272)

对我感到羞耻......

我查看了user guide,第一个函数是$this->db->insert_id();

这也适用于activerecord insert ...

编辑:我更新了链接

答案 1 :(得分:36)

上次插入ID表示您可以通过在活动记录中使用此方法来获取插入的自动增量ID

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

您可以参考此链接,您可以找到更多内容。

Information from executing a query

答案 2 :(得分:10)

对于特定表,您不能使用$ this-> db-> insert_id()。即使最后一次插入发生很久以前它也可以这样取出。可能是错的。但对我来说运作良好

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

答案 3 :(得分:8)

有助于请求ID和查询的详细信息列表

用于获取最后插入的Id:这将从表中获取最后的记录

$this->db->insert_id(); 

获取SQL查询在模态请求之后添加此项

$this->db->last_query()

答案 4 :(得分:6)

$this->db->insert_id();

试试这个你想要的问题。

答案 5 :(得分:5)

试试这个。

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

答案 6 :(得分:3)

$this->db->insert_id();

执行数据库插入时返回插入ID号

对于codeigniter-3

Query Helper Methods

答案 7 :(得分:3)

在插入查询之后,使用此命令$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.

答案 8 :(得分:1)

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

答案 9 :(得分:0)

$this->db->insert_id()  

//请尝试这个

答案 10 :(得分: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;
}

您可以在https://codeigniter4.github.io/userguide/database/helpers.html处获得有关Codeigniter 4的帮助

相关问题