Get all inserted IDs when inserting multiple rows using a single query Get all inserted IDs when inserting multiple rows using a single query php php

Get all inserted IDs when inserting multiple rows using a single query


If you like to gamble - then do this :)

To be 99% sure you would have to lock the table for writing. You are not sure that the (in future) two transactions  will not be able to intertwine.

To be 100% sure you read these values. (Or analyze the source MySQL)The best solution would be to add the date to tablei edit settings and read the latest. If you do not want to change the structure, you can use triggers http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html.

Good solution will be refresh all your settings or only pairs: key - setting name


This behaviour shouldn't be relied upon; besides the obvious locking issues, let's say you want to set up master<->master replication; all of a sudden, the id's increment by 2 every time.

Besides that, instead of actually writing multiple insert statements, it might be worth using prepared statements:

$db = new PDO(...);$db->beginTransaction();$stmt = $db->prepare('INSERT INTO `mytable` (a, b) VALUES (?, ?)');foreach ($entries as $entry) {    $stmt->execute(array($entry['a'], $entry['b']));    $id = $db->lastInsertId();}$db->commit();


I agree with @anigel. You cant be sure that some transactions wouldnt get muddled up. You can split the inserts into separate queries, call last_insert_id() for each individual query and populate an array with the results.

Granted, this may increase processing time but at least you can be sure of avoiding conflicts. Plus, since its a settings table, its highly unlikely that you'll have to run a ton of transactions per client request