7

say if I wanted to give every user that registered on my site a unique id. It seems to me that if I wanted to do this I would have to: Create a random number for the id, check to see if that id already exists in the database, if it does exist then create another random number and send yet another query to see if that exists, and so on...

This could go on for ages. Apart from having an incrementing id, is there any decent way to do this?

5
  • 2
    Why not simply use an AUTOINCREMENT field? Do users really need (or care) that they have some complicated hash that identifies them, especially if it's something they never need to see? Commented Jan 5, 2012 at 0:07
  • use an autoincrement field as your primary key. that's pretty much what everyone does. Commented Jan 5, 2012 at 0:09
  • well it will be used in the url like ?id=##### and i wanted to be adventurous :-) Commented Jan 5, 2012 at 0:09
  • 2
    Take a look: php.net/manual/en/function.mt-rand.php I guess you can run a query for current IDs, arrange results by id DESC and LIMIT1 and use that value as an optional lowest value mt_rand. Then use some reasonable number for optional highest value (maybe (olv + 100 or something like that). That way you'll get every next id higher than previous, it'll be somewhat randoms, but not more than +100 from previous id. Just an idea. Commented Jan 5, 2012 at 0:18
  • What are you trying to achieve? If you want the id to difficult to guess for security reasons, then there are better approaches (such as encryption, or by signing the id with a hash). Commented Jan 5, 2012 at 0:18

6 Answers 6

5

The best way to do this is via the auto increment function, if you really don't want to use a function like so you could use uniqid();

Basically you it generates an unique id based on milliseconds, if you put in a kinda unique prefix in the function it will generate a very unique id.

echo uniqid('prefix');

This way you won't have to check after generating an id, if it already exists or not. You can be sure it is unique.

For more information check this url http://php.net/uniqid!

Sign up to request clarification or add additional context in comments.

10 Comments

if someone was to register at the exact same time, would i not be screwed? ;p lol
No, simply use a random prefix, for example: uniqid(rand(), true). Highly unlikely that it will happen!
IP probably not a great idea as tons of users at the same business facility can have the same IP.
@Wesso seems pretty clever ;)
@JohnSmith it uses the current time as one factor when deciding which letters to select. But it can't be based purely on the time, because a high traffic site with several servers will regularly receive two requests at exactly the same microsecond.
|
1

First of all, I agree with the comments. It's all overhead code, and if you're using it to make it look interesting you should really reconsider your priorities.

But, if you still need it; here's a little something:

function uid() {
    mt_srand((double)microtime()*1000000);
    $token = mt_rand(1, mt_getrandmax());

    $uid = uniqid(md5($token), true);
    if($uid != false && $uid != '' && $uid != NULL) {
        $out = sha1($uid);
        return $out;
    } else {
        return false;
    }
}

Basically, it does a lot of random number generating to create a token for uniqueid, and then is sha's that. Probably overhead, but you can be sure that you never generate a double uid.

Fabian.

1 Comment

I have tried your code and it will generate 40 characters (maybe always). How if I want to generate only 15 or 20 characters?
1

You can use the rand() function. It will generate a random number between two.

rand(0000,9999)

It will generate a number between 0 and 9999.

To check if it already exist:

$id = rand(0000,9999);

/* CREATE YOUR MYSQL CONNECTION */
$user_list = mysql_query("SELECT * FROM users");
while ($user = mysql_fetch_array($user_list))
{
    if ($id == $user['id'])
    {
        echo('Already exist.');
    }
    else
    {
        /* YOUR CODE */
    }
}

It's the way I did it...

4 Comments

You're better off using mt_rand instead; for numbers with more randomness and it's faster too
He needs the user id to be unique. You should update your answer to demonstrate how this could be done.
Indeed, but it's simpler to use rand()... I think... I know this function 'cause I use it for my blog ID...
But it is possible to have 2 times the same id, so its not a good way to go!
0

If you have a string of 15 numbers you are looking at up to 999 trillion, I doubt it will run for "ages" considering there's almost 7 billion people on the planet.

1 Comment

I think you mean billion people, not trillion.
0

Does the ID need to be numeric? By switching to alphabetic characters you will get a lot more entropy. A 6 digit number is 1,000,000 posibilities, a 6 character alphanumeric string is 2,176,782,336 possibilities. Make it mixed case alphanumeric and that jumps to 15,625,000,000.

Here's how I usually generate unique strings that are as short as possible:

$chars = 'abcdefghijklmnopqrstuvwrxyzABCDEFGHIJKLMNOPQRSTUVWRXYZ0123456789';
mt_srand((double)microtime()*1000000);

$id = '';
do {
  $id .= $chars[mt_rand(0, strlen($chars) - 1)];
} while (isIdTaken($id));

var_dump($id);

You have to create a lot of items with this style of id, before you'll get to more than 3 or 4 characters.

Comments

-1

I know it's late for this answer but the easiest solution is to generate random number and sure it will be unique 100% is

$uid = uniqid().date("Ymdhhis");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.