I read several topics similar to what I'm asking, but none of them seemed to be very helpful to me.
I have a form where users can generate codes that are stored in a column with a Unique constraint. The codes are strings with length of 7 characters. The users can enter a number and the program generates that many codes, and this can be repeated until the maximum number of codes is reached.
My problem is with duplicate values. But not with values that are already present in the database in the moment of entering new entries(I check for those successfully), but some of the entries in the new group of (say 10000) codes are (probably) identical. So my code generates two(or more) identical codes in the same transaction and the Unique constraint in the DB complains about it.
I thought of checking the database after each entry, but it is extremely time consuming, considering we're talking about 10000 or sometimes more entries.
So now I think the only option is to modify the code that generates them in the first place, cause it seems to be inefficient and generate doubles.
A big part of the problem is the required length of the codes, otherwise I would go with pure 'uniqid()' or something similar, but since I have to restrict it to 7 characters I guess that makes it a lot worse. Also, I have to exclude some characters from the code[labeled 'problem_characters'] in the code.
Here's the code, I couldn't modify it properly to generate unique values only.
$problem_characters = array("0", "o", "O", "I", "1", 1); $code = md5(uniqid(rand(), true)); $extId = strtoupper(str_replace($problem_characters,rand(2,9),substr($code, 0, 7))); //insert $extId in the database