如何在mysql-php中检索所有最后插入的行ID? [英] How to retrieve all last inserted rows IDs in mysql-php?
问题描述
有没有一种有效的方法可以使用php从mysql数据库中检索所有最后插入的行自动递增的ID?假设我不知道要批量插入多少行,但是插入后需要所有ID.
Is there any efficient way to retrieve all last inserted rows auto incremented IDs from mysql database using php? Suppose I don't know how many rows are there to be inserted in a batch but I need all of their IDs after insertion.
在谷歌搜索之后,我没有找到任何有效的方法来执行此操作,因此我不确定是否有可能.我可以遵循这一要求,但必须多次访问数据库才能检索ID.
After Googling I didn't find any efficient way to do this, so I'm not sure is that possible. I can follow this one but have to hit database multiple times to retrieve IDs.
$data = array (
array(1,2),
array(3,4),
array(5,6)
);
$ids = array();
foreach ($data as $item) {
$sql = 'insert into table (a,b) values ('.$item[0].','.$item[1].')';
mysql_query ($sql);
$ids[] = mysql_insert_id();
}
谢谢
推荐答案
您的代码几乎是完整的解决方案.
your code is near complete solution.
$data = array (
array(1,2),
array(3,4),
array(5,6)
);
$ids = array();
foreach ($data as $item) {
$sql = "INSERT INTO `table` (`a`, `b`) VALUES ('{$item[0]}' ,'{$item[1]}');";
mysql_query ($sql) or mysql_error();
$ids[] = mysql_insert_id();
}
var_dump($ids);
如果问题是关于性能问题的,那么另一个解决方案可能是
If the question is about performance issue, then another solution could be
foreach ($data as $item) {
$sql = "INSERT INTO `table`.`table` (`a`, `b`) VALUES ('{$item[0]}' ,'{$item[1]}');";
mysql_query ($sql) or mysql_error();
}
$last_id = mysql_insert_id();
$total = count($data);
for($i = 0; $i <= $total; $i++){
$ids[] = $total-$i;
}
这将防止多个sql查询.
This will prevent multiple sql query.
这篇关于如何在mysql-php中检索所有最后插入的行ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!