gpt4 book ai didi

php - 也许 mysql_insert_id() 会返回意外的 id

转载 作者:可可西里 更新时间:2023-11-01 08:21:04 25 4
gpt4 key购买 nike

也许我的问题很愚蠢,但关于 mysql_insert_id() 我想知道一件事。在 php.net 上是这样写的:

Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).

如果在脚本到达使用 mysql_insert_id() 的行之前,另一个脚本在数据库中插入一些东西,这个函数的输出是什么?

据我所知,它将返回最后插入的项目的 ID(无论从哪里)。如果我是对的,我想知道如何避免这个问题,但是在执行插入查询时立即使用 mysql_insert_id() (因为仍然有一点机会陷入“麻烦”)。

最佳答案

它将返回在当前 session 中插入的最后一行的 ID,因此您无需担心。事实上,您将链接标识符作为参数传递,否则它默认为最后打开的链接。来自文档

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

如果你有

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());

这将始终是正确的(当然,如果 mytable 有一个 AUTO_INCREMENT 列),因为它会检索 session 中最后生成的 ID。如果同时另一个用户运行完全相同的查询,他将有一个不同的 session 并且他将正确地获得他的 id

关于php - 也许 mysql_insert_id() 会返回意外的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10109289/

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