我想在zf2中获得插入记录的id。我在php中使用scope_identity找到了解决方案。但是在zend中如何使用呢?
我的代码在indexcontroller是
<?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('ZendDbAdapterAdapter')
);
}
return $this->userTable;
}
Schema for eo_user表
eo_user
user_id | username | user_password | user_email | user_status
这里user_id是带有自动递增约束的主键。
我需要做什么改变,以找到插入记录的user_id ?
您可以使用$this->getUserTable()->getLastInsertValue();
获取插入记录的最后插入ID。
$this->getUserTable()->insert($data);
$insertedId = $this->getUserTable()->getLastInsertValue();
echo $insertedId; // will get the latest id
标题>
插入后直接调用mysql_insert_id()
函数。文档
编辑:如果这太难了,那就点击SELECT LAST_INSERT_ID();
,你就可以了
$sql = 'SELECT max(id) FROM user';
$query = $this->getAdapter()->query($sql);
$result = $query->fetchAll();
return $result[0]['max(id)'];