ZF2 How to get last insert id value?

Piotr picture Piotr · Apr 9, 2013 · Viewed 24.3k times · Source

I am stuck with getting last insert id with Zend framework 2 and I gave up on this...

There are tried combinations:

var_dump($this->tableGateway->insert($insert));
var_dump($this->tableGateway->lastInsertValue);
var_dump($this->tableGateway->getLastInsertValue());
var_dump($this->tableGateway->getAdapter()->getDriver()->getConnection()->getLastGeneratedValue());

Value is inserting to table, but every line (except first, which gives int "1") returns null. Please don't tell me, that such a big framework does not give possibility to get last insert id value!?

Answer

Jean Paul picture Jean Paul · Jun 8, 2013

Here is what I use:

$data = array()// Your data to be saved;
$this->tableGateway->insert($data);
$id = $this->tableGateway->lastInsertValue;