13

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?

karim79
  • 339,989
  • 67
  • 413
  • 406
Andrew
  • 227,796
  • 193
  • 515
  • 708

4 Answers4

16

Did you try this ? This also works fine.

//just after you call your insert($data) function .. use this
$lastInsertId = $this->getAdapter()->lastInsertId();
Amit Dugar
  • 494
  • 4
  • 9
10

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.

Cong
  • 181
  • 2
  • 5
0

Try below code:

To insert data:

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

Get Last Inserted value:

$this->tableGateway->lastInsertValue;
kwelsan
  • 1,229
  • 1
  • 7
  • 18
  • what if another user inserted a record after, the lastInsertValue would get the last inserted id in general or for the certain transaction -if used-? – Katia May 23 '14 at 18:28
0

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.

António Almeida
  • 9,620
  • 8
  • 59
  • 66