How can I get a unique value for a VARCHAR field for usernames?
I have a login-process where I would like to prefill as much as possible. The username has to be unique, so I have to get a unique, "random" string. How do I do that?
I'm currently thinking about something like this:
function getRandomString($length = 5) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $characters[rand(0, strlen($characters)-1)];
}
return $string;
}
function getUniqueVarchar($prefered) {
// Try all combinations that would make sense to the user. Eventually give an array and try to combine elements like first name / last name / birthday
$usernameTry = $prefered
$exists = Does the username $usernameTry exist?
if (!$exists) return $usernameTry;
// Maybe a year exists?
for($i=50;$i<99;$i++) {
// $exists = Does the username $usernameTry = $prefered.$i exist?
if (!$exists) return $usernameTry;
}
// Try random strings
for($i=0;$i<10;$i++) {
// $exists = Does the username $use开发者_开发知识库rnameTry = getRandomString() exist?
if (!$exists) return $usernameTry;
}
return false;
}
Does something better than my part at "// Try random strings" exist? Does MySQL (or other DB systems) have something like that built-in?
精彩评论