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

岁酱吖の 提交于 2019-12-01 14:15:02

问题


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?


回答1:


Did you try this ? This also works fine.

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



回答2:


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:


Try below code:

To insert data:

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

Get Last Inserted value:

$this->tableGateway->lastInsertValue;



回答4:


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.



来源:https://stackoverflow.com/questions/1868769/zend-framework-how-to-retrieve-the-id-of-the-last-inserted-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!