cgimusic Posted November 4, 2009 Share Posted November 4, 2009 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); }; ?> Quote Link to comment Share on other sites More sharing options...
Mchl Posted November 4, 2009 Share Posted November 4, 2009 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) Quote Link to comment Share on other sites More sharing options...
simshaun Posted November 4, 2009 Share Posted November 4, 2009 Can you not use an auto-increment'ing field in the database? And, does it have to numerical? (see this thread) Otherwise, I think Mchl's method ought to work fine. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.