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); }; ?> Link to comment https://forums.phpfreaks.com/topic/180321-solved-most-efficent-way-of-generating-an-id/ 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) Link to comment https://forums.phpfreaks.com/topic/180321-solved-most-efficent-way-of-generating-an-id/#findComment-951236 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. Link to comment https://forums.phpfreaks.com/topic/180321-solved-most-efficent-way-of-generating-an-id/#findComment-951243 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.