这个问题对我来说同样重要。有没有人有办法解决吗?当表被锁定时,是否可以使用PDO lastInsertId()?
$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版本:26年6月5日
I * *觉得你的语句根本不会执行。你在一个'prepare'中发出了多个查询。检查你的'$ sth-> execute();'的结果,如果它是假的 - 它表示失败。另外,您确定需要手动控制锁定和解锁吗? – Mjh
它执行。我检查:( 是的,我敢肯定,因为这里有更复杂的查询,这只是一个例子。) –
要显示PDO错误处理是多重语句有多糟糕,请参阅[questions/32690361 - 有趣的错误处理( (http://pastebin.com/fcBQAtxA),它一直报告成功,它显示实际发送到mysql服务器和PDO执行结果的内容 –