这个问题对我来说又很重要。有没有人有办法解决吗?
$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());
输出为:字符串(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