I have devised a solution that uses one table and some creative selecting mixed with regular expresions to achieve the desired result. Hey when you come up with a fun problem I'm more then happy to help solve it.
Attached to this post you'll find a zip file which contains two other files and php script and a sql file. Run the sql file into your database (warning if you have a users table in the database already then rename it first) configure the php script variables to access your database and you'll have a complete working example of this methodology.
Here is the function that is the meat of the solution:
function makeUser($fn,$ln,$pswd) {
//generate default username
$username = $fn . "_" . $ln;
//see if another user already has the default username and grab the ID
//if the newest record with a base username equal to the default username
$sql = "SELECT MAX(ID) FROM users WHERE Username LIKE \"$username%\"";
if($query = mysql_query($sql)) {
//get the most recent record who has a base username equal to the default username
$sql = "SELECT * FROM users WHERE ID=" . mysql_result($query,0,0);
//end the first query
mysql_free_result($query);
//if we have a record to look at
if($query = mysql_query($sql)) {
//get the username from the retrieved record
$lastun = mysql_result($query,0,'Username');
//if the username has a number on the end get that number into $num[0]
//otherwise set isNum to false
$isNum = ereg("[0-9]+",$lastun,$num);
//if this is the second user with this base name append a 1 to the end
if(!$isNum) {$username .= "1";}
//otherwise increment the highest existing number and append that to
//the default username.
else {$username .= $num[0] + 1;}
}
}
//insert the new user into the database
$sql = "INSERT INTO users (FirstName,LastName,Username,Password) VALUES (";
$sql .= "\"$fn\",\"$ln\",\"$username\",\"$pswd\")";
//report success or failure to the user
if(mysql_query($sql)) {echo "<div><br />Successfully Entered New User<br /><br /></div>\n";}
else {echo "<div class=\"error\"><br />Error Inserting User<br />$sql</font><br /><br /></div>\n";}
} //end makeUser
I've done a pretty good job comenting it but if you want anything explained just let me know.
In the attached zip file, the sql file's indentation maybe a little off my editor uses spaces sometimes and tabs sometimes. It's annoying really and I have a tool to fix it but since this is only about ten lines of very simple sql I didn't see the need. The php script has been fixed up. If the sql gives you an error on the creat table try removing the if not exists. Other then that this example should be very easy to set up and run.