Jump to content

generate unique strings of characters


needs_upgrade

Recommended Posts

Here I am sharing my code which I have written to generate unique nos. Please go through it hope It will help u out.

      function uniqueID($table){
// The length we want the unique reference number to be
$unique_ref_length = 10;
// A true/false variable that lets us know if we've
// found a unique reference number or not
$unique_ref_found = false;
// Define possible characters.
// Notice how characters that may be confused such
// as the letter 'O' and the number zero don't exist
 $possible_chars = "23456789abcdefghijklmanopqrstuvwxyz";
// Until we find a unique reference, keep generating new ones
while (!$unique_ref_found) {
            // Start with a blank reference number
    $unique_ref = "";
    // Set up a counter to keep track of how many characters have
    // currently been added
    $i = 0;
    // Add random characters from $possible_chars to $unique_ref
    // until $unique_ref_length is reached
    while ($i < $unique_ref_length) {
        // Pick a random character from the $possible_chars list
        $char = substr($possible_chars, mt_rand(0, strlen($possible_chars)-1), 1);
        $unique_ref .= $char;
        $i++;
    }
        $unique_ref = $unique_ref;
    // Our new unique reference number is generated.
    // Lets check if it exists or not
    $query = "SELECT `CommonID` FROM ".$table." WHERE `CommonID`='".$unique_ref."'";
    $result = mysql_query($query) or die(mysql_error().' '.$query);
    if (mysql_num_rows($result)==0) {
        // We've found a unique number. Lets set the $unique_ref_found
        // variable to true and exit the while loop
        $unique_ref_found = true;
    }
}
return $unique_ref;
}

Link to comment
Share on other sites

  • 3 weeks later...
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.