Reputation: 41
I have to create unique codes for each "company" in my database.
The only way I see this to be possible is to create a random number with rand()
and then check if the number exists for this "company" in the DB, if it does recreate.
My question is: Is there not a better way to do this - a more efficient way. As if I am creating 10 000 codes and there are already 500 000 in the DB it's going to get progressively slower and slower.
Any ideas or tips on perhaps a better way to do it?
EDIT:
Sorry perhaps I can explain better. The codes will not all be generated at the same time, they can be created once a day/month/year whenever.
Also, I need to be able to define the characters of the codes for example, alpha numberic or numbers only
Upvotes: 3
Views: 3188
Reputation: 20899
MySQL's UUID Function should help. http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid
INSERT INTO table (col1,col2)VALUES(UUID(), "someValue")
Upvotes: 2
Reputation: 4593
If the codes are just integers then use autoincrement or get the current max value and start incrementing it
Upvotes: 0
Reputation: 5731
I recommend you to use "Universally Unique Identifier": http://en.wikipedia.org/wiki/Universally_unique_identifier to generate your random codes for each company. In this way you can avoid checking your database for duplicates:
Anyone can create a UUID and use it to identify something with reasonable confidence that the same identifier will never be unintentionally created by anyone to identify something else. Information labeled with UUIDs can therefore be later combined into a single database without needing to resolve identifier (ID) conflicts.
In PHP you can use function uniqid for this purpose: https://www.php.net/manual/en/function.uniqid.php
Upvotes: 5