CodeIgniter Forums
insert_id() returns NULL if any field was truncated. - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: insert_id() returns NULL if any field was truncated. (/showthread.php?tid=46017)



insert_id() returns NULL if any field was truncated. - El Forum - 10-14-2011

[eluser]C. Jiménez[/eluser]
Not sure if it must be corrected (I Don't know if it a easy way to correct this behavior).
At least warned on user-guide.

If you insert data into a table and gets truncated, insert_id() will not return the id of the row.

Example:
Code:
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;

A workaround for this is validate your field with max_chars(5) to warn user. before insert the data. So you are always sure that the insert statement will not be truncated and you will retrieve your insert id.