[英]PDO Last insert ID
我正在使用$insertedId = $pdo_conn->lastInsertId();
在插入查詢后獲取最后插入的ID,然后運行另一個插入查詢:
foreach ($records as $emails_to) {
$stmt = $pdo_conn->prepare("INSERT into emails_to (email_seq, email) values (:email_seq, :email) ");
$stmt->execute(array(':email_seq' => $InsertedId, ':email' => $emails_to["email"]));
}
但它似乎無法識別最后一個插入ID,但出現此錯誤:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'email_seq' cannot be null'
我做錯了什么?
$insertedId
和$InsertedId
不相同。 變量名稱區分大小寫。
您的$insertedID
與$InsertedID
不匹配-大小寫問題
編輯; 該死,被毆打
在mysql中處理事務時要當心lastInsertId()。 以下代碼返回0而不是插入ID。 這是一個例子
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)");
try {
$dbh->beginTransaction();
$stmt->execute( array('user', 'user@example.com'));
$dbh->commit();
print $dbh->lastInsertId();
}
catch(PDOException $e) {
$dbh->rollback();
print "Error!: " . $e->getMessage() . "</br>";
}
}
catch( PDOException $e ) {
print "Error!: " . $e->getMessage() . "</br>";
}
?>
如果未引發任何異常,則lastInsertId返回0。但是,如果在調用commit之前調用了lastInsertId,則會返回正確的ID。
有關更多信息,請訪問-> PHP
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.