[英]Zend Framework: How to retrieve the id of the last inserted row?
I'm inserting a new row into my database with this code: 我用这段代码在我的数据库中插入一个新行:
$data = array(
'key' => 'value'
);
$this->getDbTable()->insert($data);
How can I get the row id of the this row that I just created? 如何获取刚刚创建的此行的行ID?
Did you try this ? 你试过这个吗? This also works fine. 这也很好。
//just after you call your insert($data) function .. use this
$lastInsertId = $this->getAdapter()->lastInsertId();
One gotcha. 一个问题。 When calling $this->getDbTable()->insert($data);
当调用$this->getDbTable()->insert($data);
you have to make sure $data include the "primary key" of your table. 你必须确保$ data包含表格的“主键”。 For example, id=null
if it's auto-increment. 例如,如果它是自动递增,则id=null
。 Otherwise, insert()
will not return the last inserted ID. 否则, insert()
将不返回最后插入的ID。
Try below code: 试试以下代码:
To insert data: 要插入数据:
$this->tableGateway->insert($data);
Get Last Inserted value: 获取上次插入的值:
$this->tableGateway->lastInsertValue;
There is also newId
function, witch returns the next new ID, so you can use it to insert a new row. 还有newId
函数,witch返回下一个新ID,因此您可以使用它来插入新行。
$id = $this->getDbTable->newId('table_name', 'id');
$data = array(
'id' => $id,
'data' => $data
);
$this->getDbTable->insertRow('table_name', $data);
Now you can do whatever you want with your $id
. 现在你可以用你的$id
做任何你想做的事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.