- This topic is empty.
-
AuthorPosts
-
December 11, 2010 at 6:54 pm #30977
Zonglars
MemberI’m trying to figure out how to generate a random, short (6-8 characters), and above all unique code that can be stored in a MySQL database. I’d probably just use numbers, because in both applications I have in mind I’m not expecting more than a few hundred results (one use is as invite codes to a small event, the other is product codes for a small shop inventory), but at the same time I’d prefer not to generate a number and then check if it’s taken. If there’s something that will convert the auto-increment number to something more random looking, that’s great too.
December 11, 2010 at 7:29 pm #70000TT_Mark
MemberMight want to check out the uniqid() PHP function and then create a substring of the result it generates?
December 11, 2010 at 7:48 pm #70001Zonglars
MemberThat’ll work, but I’m a bit confused with how I write the error handling; In the event it’s already in the database, to just keep trying. I’ve got the table set up so the code column has a unique index, so I assume I could have it try again and again if it get’s an error.
December 12, 2010 at 6:22 am #69930TT_Mark
MemberTo be honest with you. the best way to get something unique is to use the autoincrement feature, use uniqid() as specified above, use MySQL’s uuid() or generate something completely random yourself based upon the timestamp
December 12, 2010 at 8:13 am #69931Bob
MemberZonglars, do you want it to be unique or random? I don’t see the point is having random product numbers whereas I can see the point in creating unique product numbers.
Reason I’m asking is I think unique numbers would be somewhat easier by autoincrementing them, random would be harder I think.
December 12, 2010 at 3:51 pm #69936chendrix
MemberThe other option is to create a database table that has all of your IDs pre generated in them as a unique primary id field, and also has a boolean field for whether it’s been taken or not.
For a small application, having a couple hundred line database with 2 fields shouldn’t be that resource intensive.
Then, your SQL statement to check if it’s been taken or not would simply be ‘SELECT is_taken FROM codes WHERE product_id LIKE “27382” ‘
-
AuthorPosts
- The forum ‘Back End’ is closed to new topics and replies.