Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Generating a short, random, unique code to keep in database

  • This topic is empty.
Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #30977
    Zonglars
    Member

    I’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.

    #70000
    TT_Mark
    Member

    Might want to check out the uniqid() PHP function and then create a substring of the result it generates?

    #70001
    Zonglars
    Member

    That’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.

    #69930
    TT_Mark
    Member

    To 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

    #69931
    Bob
    Member

    Zonglars, 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.

    #69936
    chendrix
    Member

    The 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” ‘

Viewing 6 posts - 1 through 6 (of 6 total)
  • The forum ‘Back End’ is closed to new topics and replies.