php mysql 返回id_PHP-也许mysql_insert_id()将返回意外的ID

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值