I am currently coding a web application which I will need to create unique reference for quotes and invoices.
I wanted to create a reference that included the year and month then an reference number. i.e YYYY-MM-001.
The web application will be multi tenant and several users will be using it at the same time. One of my concerns is, how would I generate my reference without it be duplicated at the same time if there is multiple users doing the same request at the same time?
What would be the best way for me to approach this?
I am using PHP 8 and a MySQL database.
2
Answers
You can use the primary key id or any unique column, then don’t worry about the uniqueness of the data.
Use that column/id to generate a unique reference as follows :
If you’re sure you won’t have more than 999 quotes/invoices in one month, you could do something like the following…
Then to get the next values, you’ll need some queries like…
If the SELECT fails, then you insert, otherwise you update AND check that one and only one row was updated. If there’s a chance you could have more than 999 quotes in a month, then you can alter the column sizes accordingly.