views:

640

answers:

4

I'm inserting a new row into my database with this code:

$data = array(
    'key' => 'value'
);
$this->getDbTable()->insert($data);

How can I get the row id of the this row that I just created?

+10  A: 

According to the API documentation for the Zend_Db_Table_Abstract insert() method:

Inserts a new row.

  • return: The primary key of the row inserted.
  • access: public

So:

$lastInsertId = $this->getDbTable()->insert($data);
karim79
A: 

Maybe I'm doing something wrong, but when I tried that code in my model, I get the FIRST row inserted, not the last.

$db = $this->_db;
$db->beginTransaction();            

if (isset($data)) {
$lastInsertId = $db->insert('event_registrations', $data);              
}       

$db->commit();      
var_dump( $lastInsertId );

This code generates the result

int 1

rather than the last row ID. So, can someone provide me the correct way to get the ID of the last inserted row while in the model.

Mike
A: 

@Mike I think you get 1 because the method return true :)

Your code is not same as provided method. The above method use object witch store data and then write it in DB, so when you ask the object to return id it have it.

I'm not quite sure in how is suppose to happen in your scenario.

Simmol
A: 

One gotcha. When calling $this->getDbTable()->insert($data); you have to make sure $data include the "primary key" of your table. For example, id=null if it's auto-increment. Otherwise, insert() will not return the last inserted ID.

Cong