I am designing html form where users can make new PO request and save into MySQL database. PO ID will be auto generated by retrieving the last PO number from table, then increment the PO number and concatenate it with various string and date information to get a unique PO ID.
The form will show this newly generated PO ID to users before the save button is clicked (each user will assume that they are given the latest PO ID from the system).
My problem is when 2 or more users are viewing the form at the same time, they both get the same PO ID from the database before saving. Current solution: the fastest user clicking the save button will get the correct PO ID, while the rest will get error message saying the PO ID already exists, they need to refresh the page to get the next PO ID.
Kindly advise me the best practice to solve this case? am I allowed to pessimistically lock the entire Purchase Order table, wait for one user to complete the insert transaction before releasing the entire table, during this transaction what will happen to other users when they try to open the PO Input form and trying to get the latest PO number from the table?
I need to apply the best practice solution to other similar business processes (Issuing delivery notes, invoices, new customer ID registration, etc). Thank you.