我有一个查询
插入到 tbl(str)values('a'),('b'),('c')
如果我只有一个插入,那么通过使用 mysqli_insert_id($con)
我可以插入最后一个 ID,但是如何在这个多个插入查询中插入所有 ID?
最佳答案
last_insert_id()
的这种行为是 documented in the MySQL docs:
The currently executing statement does not affect the value of LAST_INSERT_ID(). Suppose that you generate an AUTO_INCREMENT value with one statement, and then refer to LAST_INSERT_ID() in a multiple-row INSERT statement that inserts rows into a table with its own AUTO_INCREMENT column. The value of LAST_INSERT_ID() will remain stable in the second statement; its value for the second and later rows is not affected by the earlier row insertions. (However, if you mix references to
LAST_INSERT_ID()
andLAST_INSERT_ID(expr)
, the effect is undefined.)
如果你真的需要它,你可以使用带有 array_push 的 foreach 来测试它
<?php
$InsetQueryArray = array(
"Insert into tbl(str) values('a')",
"Insert into tbl(str) values ('b')",
"Insert into tbl(str) values('c')"
);
$allLasIncrementIds = array();
foreach ($InsetQueryArray as $value) {
//execute it mysql
//Then use array_push
array_push($allLastIncrementIds, mysqli_insert_id($con));
}
?>
关于php - 获取最后插入的 ID 数组 mysql php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23443987/