如果例如当用户点击链接时,会自动插入一个新行,然后 php 代码请求最后插入的 id,同时插入另一行,这不会有问题吗另一个用户,所以返回的 id 实际上不是我期待的那个..?
我错了吗?有没有办法在没有“安全”漏洞的情况下做同样的事情?
(比如可能来自准备好的声明或其他内容......)
P.S id 是自动生成的。
谢谢。
最佳答案
如 manual 中所述:
LAST_INSERT_ID()
(with no argument) returns aBIGINT
(64-bit) value representing the first automatically generated value that was set for anAUTO_INCREMENT
column by the most recently executedINSERT
statement to affect such a column. For example, after inserting a row that generates anAUTO_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 anAUTO_INCREMENT
value with one statement, and then refer toLAST_INSERT_ID()
in a multiple-rowINSERT
statement that inserts rows into a table with its ownAUTO_INCREMENT
column. The value ofLAST_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 toLAST_INSERT_ID()
andLAST_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 ofLAST_INSERT_ID()
is left undefined. For manual ROLLBACK, the value ofLAST_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/