I am using $insertedId = $pdo_conn->lastInsertId();
to get the last inserted ID after an insert query then i run another insert query:
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"]));
}
but it doesn't seem to recognise the last insert ID, i get this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'email_seq' cannot be null'
what have i done wrong?
$insertedId
and $InsertedId
are not the same. Variable names are case-sensitive.
Your $insertedID
doesn't match $InsertedID
- case issue
edit; darn, beaten to the post
Beware of lastInsertId() when working with transactions in mysql. The following code returns 0 instead of the insert id. This is an example
<?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>";
}
?>
When no exception is thrown, lastInsertId returns 0. However, if lastInsertId is called before calling commit, the right id is returned.
for more informations visit -> PHP
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.