How to Get Last inserted ID in Zend Framework 2?

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();

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

DMCA.com Protection Status