How to get id of inserted record in zend framework

3k views Asked by At

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?

3

There are 3 answers

7
prava On BEST ANSWER

You can use $this->getUserTable()->getLastInsertValue(); to get last insert ID for the inserted record.

UPDATE

$this->getUserTable()->insert($data);
$insertedId = $this->getUserTable()->getLastInsertValue();
echo $insertedId; // will get the latest id
2
user3337174 On
    $sql = 'SELECT max(id) FROM user';  

    $query = $this->getAdapter()->query($sql);
    $result = $query->fetchAll();
    return $result[0]['max(id)']; 
0
LHristov On

After the insertion just call mysql_insert_id() function. Documentation

Edit: If this is too hard, then just do SELECT LAST_INSERT_ID(); and you're there