简体   繁体   English

PDO 最后插入 ID 总是正确的吗?

[英]PDO Last Insert ID always the right one?

I have the following code:我有以下代码:

<?
$query =$db->prepare("INSERT INTO a_table (id, a_field) VALUES ('', (:a_field)");
$query->bindParam(":a_field", $a_value);
$query->execute();
$last_id = $db->lastInsertId('a_table');
?>

What I want to ask is this.我想问的是这个。 Imagine when two people load the page at exactly the same time, is it a possible danger that the other persons query is inserted before the last ID is retrieved, mixing up the IDs?想象一下,当两个人完全同时加载页面时,在检索到最后一个 ID 之前插入其他人的查询,混淆 ID 是否可能存在危险?

No, this situation is impossible.不,这种情况是不可能的。 Method $db->lastInsertId() returns last inserted id for this DB conection.方法 $db->lastInsertId() 返回此数据库连接的最后插入的 id。 In other page will be another connection and another last inserted id.在其他页面将是另一个连接和另一个最后插入的 id。

PDO 将返回当前活动数据库连接插入的最后一个 ID。

Just faced following situation刚刚面临以下情况

Have file post.php which includes another file (like insert.php ).有文件post.php ,其中包含另一个文件(如insert.php )。

Whole code to insert in mysql is located in insert.php在 mysql 中插入的全部代码位于insert.php

In insert.php is code $id_of_inserted_row = $db->lastInsertId();insert.php是代码$id_of_inserted_row = $db->lastInsertId();

Then in insert.php is echo $id_of_inserted_row;然后在insert.phpecho $id_of_inserted_row; which shows correct value.显示正确的值。

But echo $id_of_inserted_row;但是echo $id_of_inserted_row; in post.php shows incorrect value (as i see shows 7 numbers less than actual value).post.php显示不正确的值(如我所见,显示的数字比实际值少 7 个)。 I do not understand why, just need to take into account.我不明白为什么,只是需要考虑。

Update更新

Sorry, above written was because inserted in two tables and mistakenly used the same $id_of_inserted_row = $db->lastInsertId();不好意思,上面写的是因为插入了两个表,错误地使用了同一个$id_of_inserted_row = $db->lastInsertId(); for both tables.对于两个表。

So i have the same conclusion as in other answers: lastInsertId() gets id of last inserted row.所以我有与其他答案相同的结论: lastInsertId()获取最后插入行的 id。

Faced situation.面临的情况。 I inserted 2 rows in mysql.我在 mysql 中插入了 2 行。 In such case i see that lastInsertId() is id of the first inserted row (not the last).在这种情况下,我看到 lastInsertId() 是第一个插入行(不是最后一个)的 ID。 Do not understand why... Found answer https://stackoverflow.com/a/12574752/2118559不明白为什么...找到答案https://stackoverflow.com/a/12574752/2118559

Important If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only.重要 如果您使用单个 INSERT 语句插入多行,则 LAST_INSERT_ID() 仅返回为第一个插入的行生成的值。 The reason for this is to make it possible to reproduce easily the same INSERT statement against some other server.这样做的原因是可以轻松地针对其他服务器重现相同的 INSERT 语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM