Using PHP and MySQL, I want to get the number of the future ID in MySQL, the number which will be after, like nextincrement. How can I do that?
Asked
Active
Viewed 292 times
0
-
You can never get next ID. Ever. Just take it from there and code your app without thinking of next ID. – N.B. Feb 15 '13 at 15:00
-
You can use `SHOW TABLE STATUS WHERE name = 'my_table'` but this gives you **no guarantee** that the next autoincrement value will be the one you get. – cmbuckley Feb 15 '13 at 15:01
2 Answers
1
It is not really possible to do reliably. You can do select max(id)+1
, but that'll fail if you've got rolled-back transactions and/or parallel processes running.
The best method is:
- Start a transaction.
- Insert a skeleton record and do a
select last_insert_id()
to get its ID - Use that ID to any child/parallel record updates
- Populate the skeleton record with anything else you need
- Commit the transaction.
If any stage fails, roll back the transaction, and throw away that ID, because it's invalid and will never be used again.

Peter Mortensen
- 30,738
- 21
- 105
- 131

Marc B
- 356,200
- 43
- 426
- 500
0
If you just insert something into the database, you can use mysqli_insert_id()
From there, just add one to get the next one.

Devyn
- 219
- 1
- 2
- 15