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.
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();
}
Thank You
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;
}
This will prevent multiple sql query.