我正在编写一个PHP类文件,它使用PDO将数据推送到MySQL数据库.本质上,文件很快被多次命中(每次都创建一个新的类实例),并且lastInsertId()方法没有跟上.例如:
//sleep(rand(100,1000)/100);
$sql = "INSERT INTO `testing` (`name`, `timestamp`) VALUES (?, ?)";
$this->dbh->beginTransaction();
$sth = $this->dbh->prepare($sql);
$sth->bindValue(1, $_POST["name"]);
$sth->bindValue(2, microtime());
$sth->execute();
$this->id = $this->dbh->lastInsertId();
$this->dbh->commit();
Run Code Online (Sandbox Code Playgroud)
如果页面被非常快速地调用两次,$this->id则返回时两个实例的值都为2,尽管DB看起来像这样:
+----+--------+-----------------------+
| id | name | timestamp |
+----+--------+-----------------------+
| 1 | Mark | 0.98705900 1385770566 |
| 2 | George | 0.99367300 1385770566 |
+----+--------+-----------------------+
Run Code Online (Sandbox Code Playgroud)
问题是执行的第一个查询应该具有id值1,并且执行的第二个查询应该具有id值2.为了解决这个问题,我添加了一个随机睡眠(上面已经注释掉)并且它纠正了问题.我正在使用交易,我认为这将纠正这个问题.我错过了一些明显的东西吗?
对于那些好奇的人,这是我的表格设置:
CREATE TABLE `testing` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`timestamp` varchar(255) NOT NULL,
PRIMARY KEY (`id`) …Run Code Online (Sandbox Code Playgroud)