Skip to content

How to Get Last inserted ID in Zend Framework 2?

Last updated on December 21, 2022

We often need the last inserted ID for different reasons(for example when you need to store a 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 a table, we can get the last Inserted ID in 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();
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments