Jump to content

[SOLVED] Most Efficent Way Of Generating An ID


cgimusic

Recommended Posts

I am using PHP to generate a random and unique 5 character, numerical ID. The code I am using is not very efficient as the more ID's are generated the more chance there is of getting more repeat ID's before a unique one is generated so I was wondering if there is a better way. The "Id_exists" function checks a MySQL database if that helps.

 

<?php
$Id=rand(10000,99999);
while(Id_exists($Id)){
$Id=rand(10000,99999);
};
?>

Link to comment
Share on other sites

One option to consider would be:

1. create MySQL table with all IDs from 10000 to 99999

2. In this table mark all ID's that are not available

3. SELECT ID FROM tableIDs WHERE available = true

4. shuffle the result

5. Take first from this array (remember to mark it as unavailable)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.