gpt4 book ai didi

php - 使用事务时 PDO lastInsertId() 是否可靠

转载 作者:行者123 更新时间:2023-11-29 01:11:21 25 4
gpt4 key购买 nike

我使用PDO交易

try {
DB::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
DB::$db->beginTransaction();

$db->prepare( insert query );
$db->execute();

$last_insert_id = $db->lastInsertId();

...
...

此脚本预计会有多个并发请求。

问题:lastInsertId() 是否可能为实际插入该行的用户返回不正确的值?

(“不正确的值”是指:由其他用户插入的 ID)。

最佳答案

你安全了。您获得的 ID 将是正确的 ID。

PDO 的 lastInsertId (在这种情况下,您的 PDO 将调用委托(delegate)给 mysql 的 last_insert_id)根据每个连接 给出最后自动生成的 ID。

来自 mysql's documentation :

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

并发连接不会破坏返回 ID 的完整性。正如您在评论中提到的,交易与此无关。只是不要忘记 promise !

我还要提到的是,如果您在同一个连接上运行多个语句,并且如果您的执行方法抛出一个未正确处理的异常,那么 lastInsertId 可能会返回最后一次成功插入的 ID联系。但它永远无法从其他用户的查询中返回 ID。

关于php - 使用事务时 PDO lastInsertId() 是否可靠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22126830/

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