skip to Main Content

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


  1. 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 :

    update invoices
    set reference = concat(date_format(now(), "%Y-%m-00"), unique_id)
    where unique_id = 1; 
    
    Login or Signup to reply.
  2. If you’re sure you won’t have more than 999 quotes/invoices in one month, you could do something like the following…

    CREATE TABLE quotes (
      id INT(14) NOT NULL AUTO_INCREMENT,
      YMFqid char(11) NOT NULL,
      PRIMARY KEY (id),
      UNIQUE KEY (YMFqid));
    
    CREATE TABLE YMnext (
      YM char(7) NOT NULL,
      next INT(3) NOT NULL DEFAULT 0,
      PRIMARY KEY (YM));
    

    Then to get the next values, you’ll need some queries like…

    SELECT next AS latest FROM YMnext WHERE YM = '2022-12';
    
    INSERT INTO YMnext VALUES ('2022-12', 0);
    
    UPDATE YMnext SET next = next + 1 WHERE YM = '2022-12' AND next = latest;
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search