Zend_Db_Table Not Returning Last Insert Id

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:

  1. //NOTE: $table is an instance of class that extends Zend_Db_Table_Abstract
  2. $data = array(‘id’=>”, ‘color’=>’blue’, ‘size’=>’large’);
  3. $id = $table->insert($data);
  4. echo $id; // –> will print an empty string
//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.

  1. //NOTE: $table is an instance of class that extends Zend_Db_Table_Abstract
  2. $data = array(‘id’=>null, ‘color’=>’blue’, ‘size’=>’large’)’
  3. $id = $table->insert($data);
  4. echo $id; // –> will print the id of the newly inserted row
//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:

  1. if ($this->_sequence === true && !isset($data[$pkIdentity])) {
  2. $data[$pkIdentity] = $this->_db->lastInsertId();
  3. }
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!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s