php Zend Framework:如何检索最后插入的行的 id?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1868769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:06:58  来源:igfitidea点击:

Zend Framework: How to retrieve the id of the last inserted row?

phpzend-frameworkzend-dbzend-db-table

提问by Andrew

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?

回答by Amit Dugar

Did you try this ? This also works fine.

你试过这个吗?这也很好用。

//just after you call your insert($data) function .. use this
$lastInsertId = $this->getAdapter()->lastInsertId();

回答by Cong

One gotcha. When calling $this->getDbTable()->insert($data);you have to make sure $data include the "primary key" of your table. For example, id=nullif it's auto-increment. Otherwise, insert()will not return the last inserted ID.

一个问题。调用时,$this->getDbTable()->insert($data);您必须确保 $data 包含表的“主键”。例如,id=null如果它是自动递增的。否则,insert()不会返回最后插入的 ID。

回答by kwelsan

Try below code:

试试下面的代码:

To insert data:

插入数据:

$this->tableGateway->insert($data);

Get Last Inserted value:

获取上次插入的值:

$this->tableGateway->lastInsertValue;

回答by António Almeida

There is also newIdfunction, witch returns the next new ID, so you can use it to insert a new row.

还有一个newId功能,女巫返回下一个新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.