How do I get the next ID to be inserted?

0

I would like to get the next ID to be inserted, something like:

$ultimoid = (DB::lastInsertId());
$futuroid = ( $ultimoid + 1 );

The purpose is to know beforehand the ID that will be used in my INSERT because before even inserting the record it is necessary to save a file in a folder whose name references the ID of this record.

    
asked by anonymous 01.01.2015 / 20:45

1 answer

4

This is a fairly common need and in other databases is solved with SEQUENCE .

Sequence is different from auto increment because using sequence you (or the framework or the database through a trigger) first gets the next ID, reserving this ID , and then, even though much later and even in another transaction, the ID can be used quietly because it will be unique - the sequence will never return that same ID again (unless it is reset ).

Unfortunately MySql does not have this feature yet, it only has simple auto increment so you can not reserve an ID.

You could create a function that behaves like a true sequence , but it is rather laborious because you have to ensure for example the concurrency control and still have to manually create a trigger for each table where please use this resource.

Here is an example of how the auto increment feature is implemented through the use of sequence in other databases: #.

    
16.01.2015 / 13:50