I want to get id of inserted record in zf2. I found solution using scope_identity in php. But how to use it in zend?
My code in indexcontroller is
<?php
public function addAction()
{
$form = new UserForm();
$request = $this->getRequest();
if ($request->isPost())
{
$form->setData($request->getPost());
if($form->isValid())
{
$data=$form->getData();
$this->getUserTable()->insert($data);
}
}
}
public function getUserTable()
{
if(!$this->userTable)
{
$this->userTable = new TableGateway('eo_user',$this->getServiceLocator()->get('Zend\Db\Adapter\Adapter')
);
}
return $this->userTable;
}
Schema for eo_user table is
eo_user
user_id | username | user_password | user_email | user_status
Here user_id is primary key with auto increment constraint.
What changes i need to do in order to find user_id of inserted record?
You can use $this->getUserTable()->getLastInsertValue();
to get last insert ID for the inserted record.
$this->getUserTable()->insert($data);
$insertedId = $this->getUserTable()->getLastInsertValue();
echo $insertedId; // will get the latest id