Louic Posted May 13, 2008 Share Posted May 13, 2008 Hello This is my first post here at phpfreaks. Hope I'll make it right. Now to my problem. I want to create a unique ID (based on diffrent letters and numbers) and save it down to my MySQL-databas (column hashid). The problem is that I don't now how to make the code loop. I'll post my code with explanation. function slumpa() { $s = chr(mt_rand(97, 122)) . chr(mt_rand(65, 90)); for ($i=0; $i<20;$i++) $s.= mt_rand(0, 9); return $s; } $regid = slumpa() $sql = "SELECT COUNT(hashid) FROM medlemmar WHERE hashid='{$regid}'"; $result = mysql_query($sql); if (mysql_result($result, 0) > 0) { [b]// Find a new unique ID and check if it is in the databas, if it is, make this until finding a unique one.[/b] } How to fix this? Quote Link to comment Share on other sites More sharing options...
p2grace Posted May 13, 2008 Share Posted May 13, 2008 Why not just md5 a timestamp? Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted May 13, 2008 Share Posted May 13, 2008 You want to set a variable to false and loop until it is true - only change it's value if you find a unique id: <?php function slumpa() { $s = chr(mt_rand(97, 122)) . chr(mt_rand(65, 90)); for ($i=0; $i<20;$i++) $s.= mt_rand(0, 9); return $s; } $unique = FALSE; while($unique === FALSE){ $s= slumpa(); $result = mysql_query("SELECT COUNT(hashid) FROM medlemmar WHERE hashid='$s'"); if(mysql_result($result,0) == 0){ $unique = TRUE; } } //insert $s into the database ?> If you're just wanting to uniquely identify a user, it'd be much easier to just use an auto-increment field, however. 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.