如何在codeigniter中获取所有插入的记录ID?我在使用insert_batch函数插入多个记录,但是codeigniter $ this-> db-> insert_id()函数仅返回最后一个记录ID。 //但是我需要所有插入的记录ID。如果有人有想法请帮助。
//In codeigniter this function returns only last inserted record id.
function insertStudent(){
$data[] = array('firstname'=>'firstname1','lastname'=>'lastname1');
$data[] = array('firstname'=>'firstname2','lastname'=>'lastname2');
$result = $this->db->insert_batch( 'student', $data );
return $this->db->insert_id();
}
答案 0 :(得分:0)
这可以通过使用第一个id和count来实现。
$this->db->insert_id()
(例如说30)获取第一个插入ID first record id - (count - 1)
(例如30 +(2-1)= 31)现在,您可以查询以获取ID在30到31之间的数据。
答案 1 :(得分:0)
如果绝对必须为每个插入的行都具有insert_id,则最简单的最可靠的方法是循环多个插入,而不是制作一个大的胖插入。
遍历多个插入将允许您获取所有insert_id。如果其中一行插入失败,并且数据库因此拒绝所有数据,那么它也将使您不会丢失所有数据。
答案 2 :(得分:0)
这是一种有效的方法:
由于您的记录具有结果ID,因此我假设它们也自动递增。
在这种情况下,您可以执行此操作,并且仍然使用insert_batch。
这是您的工作:
您要对要插入的项目进行计数:
$ count = count($ data);
运行您的批量插入:
$ this-> db-> insert_batch('student',$ data);
获取批次的第一个插入的ID:
$ first_id = $ this-> db-> insert_id();
将计数(减1)添加到插入ID中以获取最后的记录ID。
$ last_id = $ first_id +($ count-1);
您去了!现在,您将拥有插入记录的第一个和最后一个ID,并且通过扩展,可以找到介于这两个记录之间的所有其他内容。
答案 3 :(得分:0)
function insertStudent(){
$data[] = array('firstname'=>'firstname1','lastname'=>'lastname1');
$data[] = array('firstname'=>'firstname2','lastname'=>'lastname2');
$result = $this->db->insert_batch( 'student', $data );
$a= $this->db->get('student');
$data = $a->result_array();
echo($data[0]['id']);
}
希望如此对您有帮助。
答案 4 :(得分:0)
我最好的解决方案是更新DB_driver.php。
public function is_write_type($sql)
{
return (bool) (preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|REINDEX)\s+/i', $sql);
}
public function is_write_type($sql)
{
return (bool) (preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|REINDEX)\s+/i', $sql) && !preg_match('/ RETURNING /i', $sql));
}
答案 5 :(得分:0)
最安全的方法是:
code
。[id session user]-[current time stamp]
之前创建代码就足够了。code
列Select
中搜索该代码,您将在批量插入时插入所有元素