EllisLab/CodeIgniter — Issue #591: insert_id() not returning the id of the row.
Author: electropluma
Created: 2011-10-18 12:00:40+00:00
State: open

insert_id() performs a select with every field that was inserted. because of this if your DB truncated a field to fit the cell, it will return NULL.
Other unexpected behavior is if you insert a duplicate line on a table where none of the inserted fields are unique or PK.
It will return the first id found (possibly be the wrong one).

How to reproduce this:

Table example
=========================
id, nombre
-------------------------
id int(11) PK
name varchar(5)

$this->db->insert('example',array('name' => 'some text with more than 5 chars'));

$id = $this->db->insert_id();
// This performs a SELECT * from example where name = 'some text with more than 5 chars'
// Obviously 'some text with more than 5 chars' != 'some '

var_dump($id); // output null;