Reputation: 107
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?
Upvotes: 3
Views: 3109
Reputation: 376
You can get this method throw unique id.
function generate_uid(){
return md5(mktime()."-".rand()."-".rand());
}
$uniqueString = generate_uid();
Upvotes: 2
Reputation: 10061
There is a php function uniqid()
, more reference uniqid you can try this.
Upvotes: 0
Reputation: 108
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
Upvotes: 0
Reputation: 107
You can use the following to get unique id with add your prefix also:
echo md5(uniqid('myprefix_', true));
Upvotes: 0
Reputation: 3329
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))
Upvotes: 2
Reputation:
You can use AUTOINCREMENT
on your id field in the database.
It will never get duplicate since it increments the highest existing id present.
Upvotes: 3