Is it possible to get ALL inserted ID`s after multiple insert in MySQL by ONE query? Example(abstract):
$ids = array();
$parts = array();
$query = 'INSERT INTO `TABLENAME` (`FIELDS`) VALUES';
$items = array(values);
foreach($items as $item){
$parts[] = '('.$item['key1'].','.$item['key2']...','.$item['keyN'].')';
}
$query .= implode(',',$parts);
mysqli_query($link,$query);
$ids = ... // getting ALL inserted IDs
var_dump($ids);
It can do so here (one of solutions). Example(abstract):
$ids = array();
$items = array(values);
foreach($items as $item){
$query ='INSERT INTO `TABLENAME` (`FIELDS`) VALUES('.$item['key1'].','.$item['key2']...','.$item['keyN'].')';
mysqli_query($link,$query);
$ids[] = mysqli_insert_id($link);
}
var_dump($ids);
But, I would like to : one query INSERT all items - one query get ALL inserted ids.
UPDATE
My solution ( based on question generate an integer sequence in MySQL ).Return sequence of last inserted ID`s by single query.
$query_inserted_ids = "SELECT @row := @row +1 AS row_id
FROM TABLENAME , (SELECT @row := LAST_INSERT_ID()-1 )r
WHERE @row <(
SELECT id
FROM TABLENAME
ORDER BY id DESC
LIMIT 1 )";
Thanks for attention!
MySQL's
SELECT LAST_INSERT_ID()
Will return the FIRST ID returned from a multi-line insert. If you combine it with
SELECT ROW_COUNT()
you can start with the LAST_INSERT_ID() and increment by the number of records specified in ROW_COUNT().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With