也许我的问题很愚蠢,但是关于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()(因为仍然有少许机会陷入“麻烦”).
解决方法:
它将返回当前会话中插入的最后一行的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列),因为它会检索会话中最后生成的ID.如果同时另一个用户运行完全相同的查询,则他将拥有不同的会话,并且他将正确获得其ID
标签:mysql,php
来源: https://codeday.me/bug/20191201/2081182.html