php - PDO + PHP lastInsertId() 问题

标签 php mysql database pdo lastinsertid

如果例如当用户点击链接时,会自动插入一个新行,然后 php 代码请求最后插入的 id,同时插入另一行,这不会有问题吗另一个用户,所以返回的 id 实际上不是我期待的那个..?

我错了吗?有没有办法在没有“安全”漏洞的情况下做同样的事情?
(比如可能来自准备好的声明或其他内容......)

P.S id 是自动生成的。

谢谢。

最佳答案

manual 中所述:

LAST_INSERT_ID() (with no argument) returns a BIGINT (64-bit) value representing the first automatically generated value that was set for an AUTO_INCREMENT column by the most recently executed INSERT statement to affect such a column. For example, after inserting a row that generates an AUTO_INCREMENT value, you can get the value like this:

mysql>SELECT LAST_INSERT_ID();
    ->195

The currently executing statement does not affect the value of LAST_INSERT_ID(). Suppose that you generate an AUTO_INCREMENT value with one statement, and then refer to LAST_INSERT_ID() in a multiple-row INSERT statement that inserts rows into a table with its own AUTO_INCREMENT column. The value of LAST_INSERT_ID() will remain stable in the second statement; its value for the second and later rows is not affected by the earlier row insertions. (However, if you mix references to LAST_INSERT_ID() and LAST_INSERT_ID(expr), the effect is undefined.)

If the previous statement returned an error, the value of LAST_INSERT_ID() is undefined. For transactional tables, if the statement is rolled back due to an error, the value of LAST_INSERT_ID() is left undefined. For manual ROLLBACK, the value of LAST_INSERT_ID() is not restored to that before the transaction; it remains as it was at the point of the ROLLBACK.

因此,LAST_INSERT_ID() 始终是事务安全的(即使您不使用事务)。

关于php - PDO + PHP lastInsertId() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11411938/

相关文章:

php - 何时以及如何在 PHP 中使用常量?

php - 按原样存储和检索 ñ Ñ 字符

mysql - mysql 多日期范围选择

mysql - 在干净的 Ubuntu 12.04.3 LTS 上安装 MySQL 5.5 的问题

sql - 错误 : SubQuery returns more than one records

javascript - 仅使用 JavaScript 对象数组创建小型可搜索数据库。没有 AJAX,没有 PHP

java - 我可以获取任何其他浏览器窗口的 URL 吗?

php - 购买后如何更新数据库中的用户?

asp.net - 在 MySQL 中存储图片 - 聪明吗?

mysql - 关于重构sql查询