gpt4 book ai didi

php - PDO + PHP lastInsertId() 问题

转载 作者:可可西里 更新时间:2023-11-01 07:47:14 24 4
gpt4 key购买 nike

如果例如当用户点击链接时,会自动插入一个新行,然后 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com