当表先前被锁定时,是否可以使用PDO lastInsertId()?

This question is again important to me. Does anyone have a solution?

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

Output is: string(1) "lastInsertId". But when i lock table then lastInsertId is always 0. So this code always returns 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());

Conclusion: is it possible and how to get lastInsertId when table is locked? Or am I wrong somewhere?

@Ernestas I tried your suggestion and here are result :(

Code:

$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 version: 5.6.26

Answer

Everything seems fine. Try adding SELECT LAST_INSERT_ID() after unlock. I don't know why PDO does not work for you.

MySQL version: 5.5.44

Look to different answer: MySQL and PDO: Could PDO::lastInsertId theoretically fail?