Reputation: 6556
I am using auto increment value for the inserts in my table. But is there any other way to generate a unique value (which is small enough and not GUID or UUID) in php to insert as primary key in mysql?
Basically I want to get the value that is used as PK, but using auto increment I guess I cannot get the next auto increment value?
Please suggest me something on this?
Thanks.
Upvotes: 0
Views: 1919
Reputation: 1
you can use strtotime function
<?php $hash = strtotime(date('Y-m-d H:i:s')).rand(1000,9999);
Upvotes: -1
Reputation: 1570
I built a function for generating random pwds of various complexity...
Then have used...
$ukey = generatePassword(16,2).generatePassword(16,2);
for things where I want to pass an id in a url and want it to be difficult to guess. You could probably concatinate a microtime to a random string as well to make it unique and harder to guess. I don't know if this is strong enough for commerce level apps. I use this for more user account management that doesn't have anything like SSN or CCN involved.
// ---- start of function
function generatePassword($length=6,$level=2){
list($usec, $sec) = explode(' ', microtime());
srand((float) $sec + ((float) $usec * 100000));
$validchars[1] = "0123456789abcdfghjkmnpqrstvwxyz";
$validchars[2] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$validchars[3] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%&*-+";
$validchars[4] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*()_-+=/";
$password = "";
$counter = 0;
while ($counter < $length) {
$actChar = substr($validchars[$level], rand(0, strlen($validchars[$level])-1), 1);
// add current char to pwd string if it's not already in the pwd
if (!strstr($password, $actChar)) {
$password .= $actChar;
$counter++;
}
}
return $password;
}
Upvotes: 0
Reputation: 8092
You can get the last inserted autoincrement value. You want the mysql_insert_id function:
<?php
mysql_query("INSERT INTO mytable (product) values ('blah')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
The problem with having PHP generate a hash and using that as a primary key is that the hash generated could (albeit probably very rarely) be a duplicate key. Thus, you'd have to check to see if the hash is already in use, and generate more until it isn't in use.
Upvotes: 1