这个问题对我来说同样重要。有没有人有解决方案?
$conn = new PDO('mysql:dbname=test;host=127.0.0.1', 'root', '********');
$conn->exec('CREATE TABLE testIncrement ' .
'(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50))');
$sth = $conn->prepare('INSERT INTO testIncrement (name) VALUES (:name);');
$sth->execute([':name' => 'foo']);
var_dump($conn->lastInsertId());
输出为:string(1)" lastInsertId "。 但是当我锁定表时,lastInsertId总是为0。 所以这段代码总是返回0:
$conn = new PDO('mysql:dbname=test;host=127.0.0.1', 'root', 'paragraf');
$conn->exec('CREATE TABLE testIncrement ' .
'(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50))');
$sth = $conn->prepare('LOCK TABLE testIncrement WRITE; INSERT INTO testIncrement (name) VALUES (:name); UNLOCK TABLES;');
$sth->execute([':name' => 'foo']);
var_dump($conn->lastInsertId());
结论:当表被锁定时,是否可以以及如何获取lastInsertId?或者我在某处错了?
@Ernestas 我尝试了你的建议,结果如下:(
代码:
$sthLastId = $conn->prepare('SELECT LAST_INSERT_ID();');
$sthLastId->execute();
print_r($sthLastId->fetchAll());
//Output when there is no lock: **string(2) "40" Array ( [0] => Array ( [LAST_INSERT_ID()] => 40 [0] => 40 ) )**
//And output when lock is use: **string(1) "0" Array ( )**
MySQL版本: 5.6.26
答案 0 :(得分:0)
一切似乎都很好。尝试在解锁后添加SELECT LAST_INSERT_ID()
。我不知道为什么PDO不适合你。
MySQL版本: 5.5.44
查看不同的答案:MySQL and PDO: Could PDO::lastInsertId theoretically fail?