2015-09-21 48 views
0

这个问题对我来说同样重要。有没有人有办法解决吗?当表被锁定时,是否可以使用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日

+0

I * *觉得你的语句根本不会执行。你在一个'prepare'中发出了多个查询。检查你的'$ sth-> execute();'的结果,如果它是假的 - 它表示失败。另外,您确定需要手动控制锁定和解锁吗? – Mjh

+0

它执行。我检查:( 是的,我敢肯定,因为这里有更复杂的查询,这只是一个例子。) –

+0

要显示PDO错误处理是多重语句有多糟糕,请参阅[questions/32690361 - 有趣的错误处理( (http://pastebin.com/fcBQAtxA),它一直报告成功,它显示实际发送到mysql服务器和PDO执行结果的内容 –

回答

0

Answer

一切似乎罚款在解锁后尝试添加SELECT LAST_INSERT_ID()我不知道为什么PD O不适合你。

MySQL版本:44年5月5日

查找到不同的答案:MySQL and PDO: Could PDO::lastInsertId theoretically fail?

+0

我试过,同样的问题:( –

+0

你是否得到任何错误?异常?你有没有直接在sql server中尝试过?或者只在PHP中? –

+0

不,没有错误或异常我试着在sql server和SELECT_LAST_INSERT_ID中工作得很好,问题在于PDO显然。它现在但没有运气。你是否尝试像我一样重现问题,也许我的MySQL服务器有问题或PHP? –

相关问题