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

154

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

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

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

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


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

278

我真是丢人...

我看了一下用户指南,第一个函数是$this->db->insert_id();

这也适用于activerecord插入操作...

编辑:我更新了链接


29
用户指南是处理这类事情的最佳助手。我已经使用CodeIgniter两年多了,仍然会发现像这样的函数我以前从未知道过。 - Tom Schlick
8
请务必将您的插入操作和这个函数放在一个事务中,因为查询调度程序可能会在运行此函数之前插入另一个对象。 - parker.sikand
3
链接已失效,更新链接: http://ellislab.com/codeigniter/user-guide/database/helpers.html - womd
我需要使用insert_id(),但我不知道insert_id()是否授权获取它之前的insert()所属的ID!我的意思是,在另一个请求中检索属于另一个insert()的ID是否可能? - Majid

37

最后插入的ID指使用active record中的此方法可以获取插入的自增ID。

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

你可以参考这个链接,可以找到更多的资料。

执行查询后获取信息


链接不正确,请修复链接。新链接为http://www.codeigniter.com/userguide3/database/helpers.html。 - Shaiful Islam

11

对于特定的数据表,您不能使用 $this->db->insert_id()。即使最后一次插入已经很久以前,也可以像这样获取它。可能不太准确,但对我来说能够正常工作。

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

8

以下是帮助请求ID和查询的详细信息列表:

获取最后插入的ID:这将从表中获取最后一条记录。

$this->db->insert_id(); 

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

$this->db->last_query()

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

6

$this->db->insert_id();

这段代码是用于获取最后一次插入操作的主键ID值。

6

试一下这个。

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

@Dennis Decoene 你也可以访问这个链接https://ellislab.com/codeIgniter/user-guide。 - Raham

3

2
$this->db->insert_id()  

//请尝试这个


这个重复的答案对页面没有新价值,应该被删除。 - mickmackusa

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

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