在CodeIgniter Active Record中,如何获取插入查询后的最后插入ID
在使用CodeIgniter的Active Record进行MySQL数据库操作时,我们有时候会需要获取最后一次插入操作的自增ID,可以通过以下几个步骤实现:
- 在Active Record insert操作后,利用CodeIgniter的内置函数 $this->db->insert_id() 来获取最后插入的ID值。
-
如果需要在model中手动获取最后插入ID值,可以使用
$this->db->insert_id()
函数。
下面,来看一个实际的例子:
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email' => $this->input->post('email')
);
$this->db->insert('mytable', $data);
$insert_id = $this->db->insert_id();
上面的代码中,我们首先定义一个关联数组 data,键名为一个表mytable中的字段名,键值为另外一个数组中的输入值。接着,我们通过this->db->insert() 函数将该数组插入mytable表。最后,我们使用 $this->db->insert_id() 函数获取最后插入的自增ID值。
阅读更多:MySQL 教程
总结
在CodeIgniter活动记录中获取最后插入的自增ID值是一项常见的需求。通过以上简单的步骤,我们可以非常方便地获取这些值,从而提高了代码执行效率。