12

我正在使用以下代码在我的数据库中插入一个新行:

$data = array(
    'key' => 'value'
);
$this->getDbTable()->insert($data);

如何获取我刚刚创建的这一行的行 ID?

4

4 回答 4

15

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

//just after you call your insert($data) function .. use this
$lastInsertId = $this->getAdapter()->lastInsertId();
于 2011-06-22T14:42:21.820 回答
10

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

于 2010-06-27T18:33:34.597 回答
0

试试下面的代码:

要插入数据:

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

获取最后插入的值:

$this->tableGateway->lastInsertValue;
于 2013-05-25T08:59:01.293 回答
0

还有一个newId函数,witch 返回下一个新的 ID,所以你可以用它来插入一个新的行。

$id = $this->getDbTable->newId('table_name', 'id');

$data = array(
    'id' => $id,
    'data' => $data
);

$this->getDbTable->insertRow('table_name', $data);

现在你可以用你的$id.

于 2014-01-13T08:54:27.320 回答