我正在首次使用PDO,現在只是在玩它。PDO lastInsertId不適用於事務?
到目前爲止,當我嘗試做包裹在交易插入...
$this->dbh->beginTransaction();
// $sql query ran
$this->dbh->commit();
echo $this->dbh->lastInsertId();
lastInsertId()將返回0 ......當我運行在一個事務之外相同的查詢,我得到適當的身份證號碼返回。有什麼我在這裏失蹤?
我正在首次使用PDO,現在只是在玩它。PDO lastInsertId不適用於事務?
到目前爲止,當我嘗試做包裹在交易插入...
$this->dbh->beginTransaction();
// $sql query ran
$this->dbh->commit();
echo $this->dbh->lastInsertId();
lastInsertId()將返回0 ......當我運行在一個事務之外相同的查詢,我得到適當的身份證號碼返回。有什麼我在這裏失蹤?
你要問的lastInsertId()
你提交transaction
之前提交事務之前嘗試
$this->dbh->beginTransaction();
// $sql query ran
echo $this->dbh->lastInsertId();
$this->dbh->commit();
查看[this](http://www.php.net/manual/en/pdo.lastinsertid.php#85129)。 – Starx
這只是從跳出窗口中救了我。謝謝! –
調用它。 –
你已經偶然發現了一個令人討厭的PDO習慣,是的,你必須調用'lastInsertId' _before_'commit',這很痛苦,但很容易記住。 – Wrikken
@Wrikken:我不認爲它很討厭,甚至可能是有意的行爲,因爲事務通常用於執行多個INSERT語句。因此,爲了在3個INSERT語句的事務中獲得第一個INSERT語句的'lastInsertId',在執行'commit'之前,你總是必須調用'lastInsertId',因爲你' d必須在其他2個'INSERT'語句之前調用它。 –