Zend_Db_Table Not Returning Last Insert Id
Posted on November 3rd, 2008 in PHP, Web Development, Zend Framework | 4 Comments »
I just discovered a significant “gotcha” debugging some code today. Judging from the comments on a variety of blogs and forums I think many of us have had this question. To cut to the chase, if you aren’t getting your last insert id returned when you do a Zend_Db_Table insert, make sure that the array that you are inserting does not have an empty string or a zero set in the primary key field. So, if your primary key column in your database is `id` then this will cause you problems:
//NOTE: $table is an instance of class that extends Zend_Db_Table_Abstract
$data = array('id'=>'', 'color'=>'blue', 'size'=>'large');
$id = $table->insert($data);
echo $id; // --> will print an empty string
If you have to include the name of your primary key column as a key in the array you are tyring to insert, make sure it’s set to null NOT an empty string or zero.
//NOTE: $table is an instance of class that extends Zend_Db_Table_Abstract
$data = array('id'=>null, 'color'=>'blue', 'size'=>'large')'
$id = $table->insert($data);
echo $id; // --> will print the id of the newly inserted row
The reason for this is line 822 in the Zend_Db_Table_Abstract class:
if ($this->_sequence === true && !isset($data[$pkIdentity])) {
$data[$pkIdentity] = $this->_db->lastInsertId();
}
Notice the isset() condition. If primary key value in the data array you are inserting contains anything other than null then isset() will return true causing the lastInsertId() function to not get called. Hopefully this will clear things up and save us all alot of debugging time!
4 Responses
Thank you!
been searching for maybe years lol
nah kidding. awesome, works like a charm
Thank you!
I’ve pulled my hairs several hours trying to figure this out.
Thanks!
Good one man. I lost quite some time with this one today