0

I have a problem when submitting a form, when the data is sent to create in the database, if 2 requests arrive at the same time 2 records are created with the same code, there is a column (not the primary key, not auto-incrementing) formed by characters and numbers and each time a record is created the id is increased.

I am using php and mysql,it is very unlikely that it will happen but it has happened, how could I avoid this? Thank you

fab1308
  • 1
  • 2
  • 1
    If you want unicity in your DB, just create a unique index on this field and handle unicity constraint errors (https://www.mysqltutorial.org/mysql-unique-constraint/) in your code. – acorbel May 03 '21 at 16:41
  • 2
    *"each time a record is created the id is increased"* - Then why not use an auto-incrementing field? It sounds like it [doesn't need to be the primary key](https://stackoverflow.com/a/14087703/328193). – David May 03 '21 at 16:43
  • It is a column similar to a primary key since it must be unique but it is made up of characters and numbers, the problem is that if I send 2 forms with different information from different places but at the same time the 2 records with different information are created but they remain with the same code. – fab1308 May 03 '21 at 16:46
  • Either you need to fix how the key is generated or use unique indexes as suggested and handle duplicate key errors. – Shadow May 03 '21 at 16:49
  • 1
    You need a better **sequence generator**. You need one that avoids *race conditions*. – tadman May 03 '21 at 17:00
  • A query is made to obtain the last number created, it is increased by 1 and then it is concatenated with a text, this in a function that returns this code – fab1308 May 03 '21 at 17:06
  • 2
    That's a classic example of a race condition: Fetch, increment and set. You can't do that. You need an *atomic statement*. There are many examples of sequence generators that do this correctly and reliably. Find one and adapt to your needs. – tadman May 03 '21 at 17:27
  • Thank you very much everyone for the help – fab1308 May 03 '21 at 17:57

0 Answers0