简体   繁体   English

PHP PDO :: lastInsertId()返回0

[英]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 SQL表

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文件

<?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? 当应该返回6时,它将返回0。问题出在哪里?

You must use $db->lastInsertId() before you commit if you are in a transaction. 如果您正在事务中,则在提交之前必须使用$db->lastInsertId() Even if you rollback a transaction, the id is "used" or skipped, which is why you should not depend on IDs to be sequential. 即使回滚事务,该ID也会“使用”或被跳过,这就是为什么您不应该依赖ID顺序的原因。

Use this 用这个

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

instead 代替

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

I have removed the NULL . 我已经删除了NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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