4

How can I generate a unique Key and insert it into my mysql database?
This is what I currently use:

echo uniqid(time(), true);

Can you tell me wether it is a unique key or not?

1
  • 6
    Why not let MySQL handle it using an auto incrementing number? Commented Nov 12, 2013 at 10:30

6 Answers 6

3

You can use AUTOINCREMENT on your id field in the database.
It will never get duplicate since it increments the highest existing id present.

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

Comments

2

you can use following to get unique id with 32 chars

md5(uniqid(time(), true))

or you can use sha1 like with 40 chars

sha1(uniqid(time(), true))

3 Comments

md5 does not always create a unique hash. It has collisions.
For my need this answer is perfect :)
Note that the resulting string can be guessed, see the Warning in PHP documentation: php.net/manual/en/function.uniqid.php So you should not use in a URL or an auth system since an attacker can brute-force this.
2

You can get this method throw unique id.

function generate_uid(){
    return md5(mktime()."-".rand()."-".rand());
}

$uniqueString  = generate_uid();

Comments

0

You can use the following to get unique id with add your prefix also:

echo md5(uniqid('myprefix_', true));

Comments

0

Try this for a unique string

    function gen_random_string($length=16)
        {
            $chars ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";//length:36
            $final_rand='';
            for($i=0;$i<$length; $i++)
            {
                $final_rand .= $chars[ ran

d(0,strlen($chars)-1)];

        }
        return $final_rand;
    }

    echo gen_random_string()."\n"; //generates a string
    echo gen_random_string(8)."\n"; //generates a string with length 8

Comments

0

There is a php function uniqid(), more reference uniqid you can try this.

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.