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);
};
?>

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)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.