Jump to content

Create unique ID


Louic

Recommended Posts

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?

Link to comment
Share on other sites

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.

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.