-1

I have to generate in PHP invoices with incremental numbers starting from 1. My idea is to create a table with an autoincrement field starting from 1. When a user makes a payment, I look at the table for the last entry saved, I get its field value (the autoincrement one) and I make +1 to generate the invoice number and I save a new entry with the new invoice number to keep track of it. Is my idea correct or not? What about if 2 users looked at the table at the same time (2 queries)? In this case they will both get from it the same last saved value and will end up with the same invoice numbers generated. Is this something that can happen? Tahnks.

oussama kamal
  • 1,027
  • 2
  • 20
  • 44
  • 1
    No, that isn't the correct approach... the whole point of autoincrement is that it does that work for you, and does it safely.... insert a new empty invoice to get the number, then update it with the details – Mark Baker Jun 20 '17 at 22:14

2 Answers2

0

There is no need for inserting the new value because the autoincrement do that for you, if you need to track the correct invoice number onscreen, I suggest a temp table that keeps the invoice number assigned to that user, so when 2 or more users are working they will have diferent invoice numbers on screen, you can make a query that check the max id on both tables so it will never be duplicated on screen.

Although with the autoincrement id it shouldn't duplicate the invoice numbers.

0

No, don't do it this way. If you need to display an invoice number when the user first goes to create one, create the entry in the database on first display, you can then display this number on the screen, then update that invoice with the relevant updates to the invoice.

Without knowing what framework you're using, typically when you do an Insert command there is a return from it that allows you to access the auto-incremented ID.

Rudiger
  • 6,749
  • 13
  • 51
  • 102
  • The return of the insert command tells you the number of rows that have been affected. You can't know the new auto-incremented ID from there. But if there is going to be a select after the insert query, then there should be added more criteria except the max ID in order to restrict the danger of getting the wrong inserted row. – Vasiliki M. Jun 20 '17 at 23:54
  • @VassilikiM. you're right sorry however you can get the ID from one of the functions according to the library you're using that returns it based on the current connection which will prevent issues with concurrency in OPs question. https://stackoverflow.com/questions/1685860/how-do-i-get-the-last-inserted-id-of-a-mysql-table-in-php – Rudiger Jun 21 '17 at 01:43
  • Oh I didn't know those alternatives. Although I believe that the inner logic of these calls will probably hide a SELECT method which no matter what does the same thing but doesn't affect us anyway, so it's a good solution. Thanks for mentioning it! – Vasiliki M. Jun 21 '17 at 02:03