Posted by Arjun on Tuesday 22nd April 2014

How to Get Last inserted ID in Zend Framework 2?

Last Inserted ID

We often need last inserted ID for different reasons(for example when you need to store foreign key), Immediately after a record has been inserted into the database, you can get the id that was auto incremented(primary Key).

    $data = array();       
    $this->tableGateway->insert($data); // insert into database table 

After Inserting data into table , we can get Inserted ID the following ways

Using Abstract Table Gateway Property :

The ZendDbTableGatewayAbstractTableGateway specifies a $lastInsertValue Property

        echo $this->tableGateway->lastInsertValue;
   

Using Abstract Table Gateway Method :

The ZendDbTableGatewayAbstractTableGateway specifies a getLastInsertValue() method

        echo $this->tableGateway->getLastInsertValue();

Using Abstract Table Gateway Method :

The ZendDbAdapterDriverDriverInterface specifies a getLastGeneratedValue() method

        echo $this->tableGateway->adapter->getDriver()->getLastGeneratedValue();
// or
       echo $this->tableGateway->adapter->getDriver()->getConnection()->getLastGeneratedValue();