Zend Framework: How to retrieve the id of the last inserted row?
Asked Answered
M

4

13

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?

Militarism answered 8/12, 2009 at 18:4 Comment(0)
C
16

Did you try this ? This also works fine.

//just after you call your insert($data) function .. use this
$lastInsertId = $this->getAdapter()->lastInsertId();
Cipolin answered 22/6, 2011 at 14:42 Comment(0)
M
10

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.

Machine answered 27/6, 2010 at 18:33 Comment(1)
One note, this is already marked as fixed in v1.11.6. See framework.zend.com/issues/browse/ZF-3837Syphilis
A
0

Try below code:

To insert data:

$this->tableGateway->insert($data);

Get Last Inserted value:

$this->tableGateway->lastInsertValue;
Allover answered 25/5, 2013 at 8:59 Comment(1)
what if another user inserted a record after, the lastInsertValue would get the last inserted id in general or for the certain transaction -if used-?Kati
C
0

There is also newId function, witch returns the next new ID, so you can use it to insert a new row.

$id = $this->getDbTable->newId('table_name', 'id');

$data = array(
    'id' => $id,
    'data' => $data
);

$this->getDbTable->insertRow('table_name', $data);

Now you can do whatever you want with your $id.

Capitulary answered 13/1, 2014 at 8:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.