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

Den*_*ene 150 php codeigniter

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

$last_id = $this->db->insert('tablename',
    array('firstcolumn' => 'value',
    'secondcolumn' => 'value')
);
Run Code Online (Sandbox Code Playgroud)

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

这样您就可以在以下代码中使用insert id.

Den*_*ene 276

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

我查看了用户指南,第一个功能是$this->db->insert_id();

这也适用于activerecord插入...

编辑:我更新了链接

  • 对于像这样的事情,用户指南是你最好的朋友.我已经使用codeigniter 2年以上,我仍然发现这样的功能,我从来不知道. (28认同)
  • 确保将insert和this函数包装在事务中,因为查询调度程序可能会在运行此函数之前插入另一个对象 (7认同)
  • 链接已死,更新链接:http://ellislab.com/codeigniter/user-guide/database/helpers.html (3认同)

小智 37

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

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

你可以参考这个链接,你可以找到更多的东西.

执行查询的信息


小智 10

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

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


Mad*_*hur 8

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

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

$this->db->insert_id(); 
Run Code Online (Sandbox Code Playgroud)

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

$this->db->last_query()
Run Code Online (Sandbox Code Playgroud)


小智 6

$this->db->insert_id();

试试这个你想要的问题.


小智 6

插入查询后,使用此命令$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.
Run Code Online (Sandbox Code Playgroud)


Rah*_*ham 5

试试这个.

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