Zend Framework: How to retrieve the id of the last

2019-02-21 09:28发布

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?

4条回答
Explosion°爆炸
2楼-- · 2019-02-21 10:05

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

查看更多
狗以群分
3楼-- · 2019-02-21 10:10

Try below code:

To insert data:

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

Get Last Inserted value:

$this->tableGateway->lastInsertValue;
查看更多
冷血范
4楼-- · 2019-02-21 10:11

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

$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.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-02-21 10:15

Did you try this ? This also works fine.

//just after you call your insert($data) function .. use this
$lastInsertId = $this->getAdapter()->lastInsertId();
查看更多
登录 后发表回答