简体   繁体   中英

PHP PDO::lastInsertId() returns 0

Thanks in advance for reading this, I couldn't find an answer that solved my problem... I don't understand what I'm doing differently than the tutorials/suggestions I found:

SQL Table

CREATE TABLE IF NOT EXISTS `LastInsertID` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(150) NOT NULL,
  `email` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;

PHP File

<?php

// Connect to database
$user = "foo";
$pswd = "bar";

$db = new PDO( 'mysql:host=localhost;dbname=test', $user, $pswd );
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Prepare request
$rq = $db->prepare('INSERT INTO `LastInsertID` VALUES(NULL,:name,:email)');

// Begin and commit request
$db->beginTransaction();
$values = array('name'=>'Foo','email'=>'bar@baz.com');
$rq->execute($values);
$db->commit();

// Echo last ID
echo $db->lastInsertId();

?>

This returns 0 when it should return 6. Where is the problem?

You must use $db->lastInsertId() before you commit if you are in a transaction. Even if you rollback a transaction, the id is "used" or skipped, which is why you should not depend on IDs to be sequential.

Use this

INSERT INTO `LastInsertID` (name, email) VALUES(:name,:email)

instead

INSERT INTO `LastInsertID` VALUES(NULL,:name,:email)

I have removed the NULL .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM