Hard to explain, and let me show an example.
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.