PDO for MySQL的lastInsertId是否存在竞争条件? [英] PDO's lastInsertId for MySQL a race condition?

查看:64
本文介绍了PDO for MySQL的lastInsertId是否存在竞争条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个PHP类文件,该文件使用PDO将数据推送到MySQL数据库.本质上,文件会很快被击中很多次(每次都创建该类的新实例),并且lastInsertId()方法没有跟上.例如:

I'm writing a PHP class file which pushes data to a MySQL database using PDO. Essentially the file gets hit many times very quickly (creating a new instance of the class each time), and the lastInsertId() method isn't keeping up. For example:

//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();

如果很快两次调用该页面,则返回$this->id时,两个实例的值均为2,尽管DB看起来像这样:

If the page is called twice very quickly, when $this->id is returned both instances have the value of 2, despite the DB looking like this:

+----+--------+-----------------------+
| id | name   | timestamp             |
+----+--------+-----------------------+
|  1 | Mark   | 0.98705900 1385770566 |
|  2 | George | 0.99367300 1385770566 |
+----+--------+-----------------------+

问题在于,执行的第一个查询的id值应为1,执行的第二个查询的id值应为2.为解决这个问题,我添加了一个随机睡眠(上面已注释) ),它可以解决此问题.我正在使用交易,我相信这可以纠正此问题.我在这里遗漏了什么明显的东西吗?

The problem is that the first query executed should have an id value of 1, and the second query executed should have an id value of 2. To get around this, I added a random sleep (commented out above) and it corrects the issue. I am using transactions, which I believed would rectify this issue. Am I missing something obvious here?

对于那些好奇的人,这是我的餐桌设置:

For those curious, here's my table setup:

CREATE TABLE `testing` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(255) NOT NULL,
    `timestamp` varchar(255) NOT NULL,
     PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

PHP 5.3.3
MySQL 5.1.69

PHP 5.3.3
MySQL 5.1.69

推荐答案

事实证明,问题在于Chromium的内置控制台的网络"选项卡未显示正确的信息.通过console.log()显示ID可以按预期工作,并且使用FireBug for Firefox可以按预期显示网络活动.我假设网络标签会显示实际的网络活动,但并非总是如此.

The issue turned out to be that Chromium's built-in console's network tab does not show the correct information. Showing the ID via console.log() works as expected, and using FireBug for Firefox shows the network activity as expected. I was working under the assumption that the network tab would show the actual network activity, which it does not always.

这篇关于PDO for MySQL的lastInsertId是否存在竞争条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆