getting last inserted row id with PDO (not suitable result)

偶尔善良 提交于 2019-12-06 14:31:40

Run "SELECT LAST_INSERT_ID()" query.
If returned ID is still 19, not 2 (or whatever primary key should be after all tries), there is a problem with MySQL, irrelevant to PDO. You have to investigate it as a separate case (and, probably, separate question), supplying full SQL proof-code, able to run in console, involving creating a table, running insert and selecting LAST_INSERT_ID()

If this function returns the right value but PDO still wrong one - you have to probably bugreport it on bugs.php.net, again with full reproduceable code and all software names with exact version numbers provided.

Only one thing to make it clear: are you certainly sure that $sql variable in your question contains proper INSERT statement, not something like INSERT ON DUPLICATE or such? Or are there any triggers set on this INSERT?

I looked at PDO::lastInsertId() recently but found the description in the manual insufficiently convincing (or indeed comprehensible) and so opted for using something like this instead:

...
$stmt->execute();
$row = $stmt->fetch();
...

which seems to work for me.

I'm no PDO or MySQL expert, so this may not be quite right, but I also thought that the above approach would circumvent the possible problem of another row being inserted in the database (by a different user/thread) in between this thread's execute() and lastInsertID() calls.

If you're keen to keep lastInsertID() have you investigated whether, in your setup, the ID returned has to be an auto-increment field? The manual sort of hints that this should be so but is hopeless vague (IMHO).

Hope that's of some help.

Cheers, Ian.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!