[英]How to get id of inserted record in zend framework
I want to get id of inserted record in zf2. 我想在zf2中获取插入记录的ID。 I found solution using scope_identity in php.
我在php中找到使用scope_identity的解决方案。 But how to use it in zend?
但是如何在zend中使用它?
My code in indexcontroller is 我在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('Zend\Db\Adapter\Adapter')
);
}
return $this->userTable;
}
Schema for eo_user table is eo_user表的架构为
eo_user
user_id | username | user_password | user_email | user_status
Here user_id is primary key with auto increment constraint. 这里的user_id是具有自动增量约束的主键。
What changes i need to do in order to find user_id of inserted record? 为了找到插入记录的user_id,我需要做哪些更改?
You can use $this->getUserTable()->getLastInsertValue();
您可以使用
$this->getUserTable()->getLastInsertValue();
to get last insert ID for the inserted record. 获取插入记录的最后一个插入ID。
$this->getUserTable()->insert($data);
$insertedId = $this->getUserTable()->getLastInsertValue();
echo $insertedId; // will get the latest id
After the insertion just call mysql_insert_id()
function. 插入后,只需调用
mysql_insert_id()
函数即可。 Documentation 文献资料
Edit: If this is too hard, then just do SELECT LAST_INSERT_ID();
编辑:如果这太难了,那么只需执行
SELECT LAST_INSERT_ID();
and you're there 你在那里
$sql = 'SELECT max(id) FROM user';
$query = $this->getAdapter()->query($sql);
$result = $query->fetchAll();
return $result[0]['max(id)'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.