mysql_insert_id() 在 php 中,不返回最后一个插入 id


mysql_insert_id() in php , not return last insert id?

这是我的Mysql查询。在我的表中,Id 是自动增量类型。

$sql ="INSERT INTO product_detail (master_detail_id,Product_code,Product_label) 
values
('8330','TOTAL','products'),('8330','010290','demo'),('8330','010639','Live demo'),
('8330','020900','demo fat'),('8330','030344','demos')";
 $insertDetails = mysql_query( $sql);
echo "last insert id-->".mysql_insert_id();

我得到了最后一个插入 id--->1,但我应该得到它 5。我不知道为什么会这样?

表结构

     id            bigint(250)  No  None    AUTO_INCREMENT  
Product_code       varchar(20)  latin1_swedish_ci       No  
Product_label      varchar(500) latin1_swedish_ci       No  
master_detail_id   bigint(250)          No  None    

在多行 INSERT 语句的情况下,mysql_insert_id() 返回第一个自动生成的AUTO_INCREMENT值;如果没有生成这样的值,它将返回插入AUTO_INCREMENT列中的最后一个显式值。

如果将 id 列指定为 AUTO_INCREMENT,mysql_insert_id() 将返回 id。你应该知道,如果你的id列是BIGINT类型的结果,哪个函数返回可能是错误的(这也在php文档中指定:http://php.net/manual/en/function.mysql-insert-id.php)

对于多插入mysql_insert_id() 返回第一个,您需要执行 5 个单独的查询,在最后运行 mysql_insert_id(),或者执行 1 个额外的查询

SELECT MAX(master_detail_id) FROM product_detail or 
SELECT master_detail_id FROM product_detail 
ORDER BY master_detail_id DESC LIMIT 1

它只会返回插入的第一个项目的 ID,根据文档,mysql_insert_id() 从 5.5.0 开始被弃用。

考虑改用 mysqli_insert_id()

要解决此问题,您可以尝试使用 LAST_INSERT_ID() Mysql 函数

引用文档:

Performing an INSERT or UPDATE statement using the LAST_INSERT_ID() function will also modify the value returned by the mysqli_insert_id() function.

一个简单的方法是在插入数据后选择最后一个 id如果有人能指出正确的方法,这可能是错误的?

$sql ="INSERT INTO product_detail (master_detail_id,Product_code,Product_label) 
values
('8330','TOTAL','products'),('8330','010290','demo'),('8330','010639','Live demo'),
('8330','020900','demo fat'),('8330','030344','demos') select LAST_INSERT_ID() from `product_detail`";

重要

请注意,如果最后一次插入失败,LAST_INSERT_ID()将未定义,因此您需要添加检查!

由于您正在取消表,因此自动增量值将重置为 1 。因此,每当您运行查询并询问最后插入的 id 时,它都会返回 1 .