This topic is locked

Ensure unique username auto creation loop

9/30/2011 10:34:50 AM
PHPRunner Tips and Tricks
F
FunkDaddy author

A project I was working on required usernames to be automatically generated based on a persons first name or last name (for simplicity sake in this example assume that we will always have at least one of those two variables).
In a form's "After Update" and/or "After Insert" (depending on your use case)



//Let's prep the fields to prevent issues when creating username to ensure no spaces and ensure no illegal characters when inserting in MySQL

$Parent_1_First_Name = addslashes(str_replace(" ","",$values["Parent_1_First_Name"]));

$Parent_1_Last_Name = addslashes(str_replace(" ","",$values["Parent_1_Last_Name"]));
//Here if first name is null or empty we use last name, otherwise simply use first name. Either one used gets appended with random number between 99 and 999

if($Parent_1_First_Name == null OR $Parent_1_First_Name == ""){

$Parent_1_Login = strtolower($Parent_1_Last_Name).rand(99,999);

}else{

$Parent_1_Login = strtolower($Parent_1_First_Name).rand(99,999);

}
global $conn;

//Check for existing user names and loop through as many times as necessary until a unique one is generated

//This will loop through and keep appending additional random number between 10 and 99 to the username until it finds a unique one (no duplicate)

do

{

$Parent_1_Login = $Parent_1_Login . rand(10,99);

$sql = "SELECT Username FROM users_tbl WHERE Username ='".$Parent_1_Login."'";

$rs = db_query($sql,$conn);

$num_rows = mysql_num_rows($rs);

}

while($num_rows > 0);
//hereafter you would proceed with inserting the username into whatever user table used to control the login to your app (not adding code here because there are plenty of exmaples on how to do this in the forums)


Cheers,