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

标签 php mysql

也许我的问题很愚蠢,但关于 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/

相关文章:

php - 使用 PHP 在不同页面中发布变量以创建动态表

javascript - ajax 和 php 中的复选框决策

php - Cakephp多层次关系

javascript - 在网站中处理 SQL 响应的位置

mysql - 将多个内容添加到mysql中的列x行位置

java - MySQL 日期和时间插入错误

sql - oracle sql developer 编辑字段

php - 使用 smarty 编译 product.tpl 时出错

php - 查询是来自 jquery 的空 mysql php 变量

php - 通过 Nix flake 安装时,Composer 读取的 PHP 版本不正确