php pdo 的 lastInsertId 返回值是否可信???

test 表 DDL

create table test (
    id int primary key not null auto_increment , 
    name varchar(500)
)

场景

获取插入记录的ID

非事务方式

$pdo = new PDO('mysql:host=127.0.0.1;dbname=test' , 'root' , '123456');
$stmt = $pdo->prepare("inset into test (name) values (:name)");
$stmt->execute([
    ':name' => 'test'
]);

// 获取刚插入记录的id
var_dump($pdo->lastInsertId());

这边我特怀疑他的正确性,毕竟用了两条语句,在第一个插入语句执行完毕后,也许在还未触发 lastInsertId 之前又有一个进程插入了一条数据,那 lastInsertId 的结果就错误了,请问是否会存在这样的现象??

事务方式

$pdo = new PDO('mysql:host=127.0.0.1;dbname=test' , 'root' , '123456');
$pdo->beginTransacation();

try {
    $stmt = $pdo->prepare("inset into test (name) values (:name)");
    $stmt->execute([
        ':name' => 'test'
    ]);
    
    // 获取刚插入记录的id
    var_dump($pdo->lastInsertId());
    $pdo->commit();
} catch() {
    $pdo->rollBack();
}

这边能保证获取的 id 的正确性,但由于事务不能嵌套,而我有在学习 Laravel 数据库操作语句的时候,有下面这种:

\DB::transaction(function(){
    \DB::table('test')->insertGetId([
        ':name' => 'test'
    ]);
});

请问这边的 isertGetId 的实现方式是??
求解惑...

阅读 5.9k
1 个回答
可以这样测试
$pdo = new PDO('mysql:host=127.0.0.1;dbname=test' , 'root' , '123456');
$stmt = $pdo->prepare("inset into test (name) values (:name)");
$stmt->execute([
    ':name' => 'test'
]);
sleep(5);
// 获取刚插入记录的id
var_dump($pdo->lastInsertId());

另起一个进程插入一条数据.

没用过laravel ,看了下thinkphp5 的源码
getLastInsID 使用的是PDO 的 lastInsertId

clipboard.png

$this->linkID PDO 当前连接ID

也就是说通过这个ID获取的自增ID是属于当前对象的最后一次插入值的ID
并不是简单的获取最后一条数据的ID。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题