0

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 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 Answers2

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:

  1. Start a transaction.
  2. Insert a skeleton record and do a select last_insert_id() to get its ID
  3. Use that ID to any child/parallel record updates
  4. Populate the skeleton record with anything else you need
  5. 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.

http://php.net/manual/en/function.mysql-insert-id.php

Devyn
  • 219
  • 1
  • 2
  • 15