Hard to explain, and let me show an example.
$getname = $_POST['getname'];
$i++;
$q = "SELECT username FROM User WHERE username LIKE '".$getname."%'";
$r = mysql_query($q);
if(mysql_num_rows($r) > 0){
while($row = mysql_fetch_object($r)){
if($row->username == $getname){
$uname = $getname.$i;
}else if($row->username == ($getname.$i)){
$uname = $getname.$i+1;
}
$i++;
}
}
else
{
$uname = "foo";
}
First, lock the table so no other table will write to it at the same time. then do something like this:
$name = 'foo';
$first_name = $name;
$i = 0;
do {
//Check in the database here
$exists = exists_in_database($name);
if($exists) {
$i++;
$name = $first_name . $i;
}
}while($exists);
//save $name
Another method is to select all names in the table starting with "foo" and ending in a number and then finding the largest number. This can be done in SQL.
The first method is better for use cases with only a small risk of collision, since the pattern matching may be slow, but if you have a lot of collisions the latter may be better.