以下场景。
我们有 2 个脚本,都插入到表中,然后使用 lastInsertId()
从自动增量列中获取值。
如果这 2 个脚本并行执行,我们是否确定它们不会弄乱结果?
实时:
时间 1:脚本 1 -> 插入。 (创建 id = 1)
时间 1:脚本 2 -> 插入。 (创建 id = 2)
(数据库可能使用锁/信号量处理此问题)
Q1. 时间 2:脚本 2 -> lastInsertId() 返回 1 或 2?它是确定性的吗?
Q2.顺序插入怎么样?
script.php
$statement1->insert('john'); // id = 1
$statement2->insert('mary'); // id = 2
echo $statement1->lastInsertId();
// is it 1 or 2? Is this also deterministic?
最佳答案
是的,它是可靠的。
顾名思义,lastInsertId()
保存最后插入行的 id(主键)。
因此关于Q1:答案将是 2,因为那是最后插入的行。
当涉及到顺序插入时,并且您想“做某事” 围绕lastInsertId()
的使用,那么您将必须声明lastInsertId()
完全 在(这很重要)执行的查询行之后。这样您就可以确保拥有您要使用的 id。
->an insert query is executed
->lastInsertId() is stored into a variable
->variable is used for something
->another insert query is executed
->another lastInsertId is stored into a variable
->variable is used for something.
etc...
同样的逻辑也适用于循环。
您不一定必须将 lastInsertId()
存储到变量中,但如果您使用 PHP 工作并且需要将它用于多种用途,那么这样做是有意义的。如果没有,那么您可以直接在相关查询中直接使用它。但请记住,它必须恰好在您希望使用的 id 的指定插入之后。
失败逻辑示例:
<?php
//I want to get id 1
$statement1->insert('john'); // id = 1
$statement2->insert('mary'); // id = 2
$lastId=$statement1->lastInsertId();
?>
这将是一个失败的逻辑,因为我的意图是检索 id 1,但由于我正在等待在语句 2 而不是语句 1 之后检索我的 lastInsertId()
,所以我的 lastInsertId()
将等于 2 而不是 1。
工作逻辑:
<?php
//I want to get id 1
$statement1->insert('john'); // id = 1
$lastId=$statement1->lastInsertId();
//do something with $lastId? (value will be 1)
//get contact info from a theoretical contact info table
$sql="SELECT * FROM tbl_contacts WHERE userId='$lastId'";
$statement2->insert('mary'); // id = 2
$lastId=$statement2->lastInsertId();
//do something with $lastId? (value will be 2)
?>
这个逻辑会起作用,因为我正在检索我想要的 id 值,并在它们被另一个 id 覆盖之前使用它们。
当然,您可以使包含 lastInsertId()
值的变量是唯一的,这样它们就不会被覆盖,然后您可以随时使用它们。
关于php - 最后插入 id 的方法可靠吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52736203/