如果名称存在,则保存为名称(1)名称(2),依此类推

There's a mysql database that stores ids and names, when users are creating names with a form they can create existent names since unique ids are the ids such as:

d49f2c32f9107c87c7bb7b44f1c8f297 name
2fa9c810fbe082900975f827e8ed9408 name

what i want to do is saving the second "name" -> "name(1)" when inserting into database.

So far what I've got is this as the idea

lets say the name entered is 'name'

$input = 'name';

select the name we want to check from mysql database

mysql_query(SELECT * FROM  `table` WHERE  `name` =  '$input');

if the result exists, then insert as $input.'(1)'

my question is what if name exists, and name(1) also exists, then how can i add the name(2) there...

$i = 1;
$sourceName = $name;
while( sql "SELECT COUNT(*) FROM table WHERE name = '$name'" ) {

  $name = $sourceName.' ('.$i.')';
  $i++;
}

At this point you have the final $name (with $i counting the iteration)

You could return the number of people with that name in the database, then add 1 to that number.

SELECT COUNT(id) FROM table WHERE name LIKE '$input(%)');

Something like this should do the trick:

SELECT * FROM table WHERE name = '$input' OR name LIKE '$input(%)'

Note that for this to work, you'd need to escape any percent signs in $input in the LIKE clause, otherwise they'll be treated as wildcards.

Use a regex that checks for integers between two parentheses at the end of the string. If there exists an integer, add 1 to it.

You could also attempt to do it the other way around, make name field unique and try to input it in a while loop, if it fails add ($i) and do $i++ every iteration.

//edit: The problem with using solutions that do a like comparison is that you will get false positives, for instance $hi% will also count hippie. Which gives you unnecessary (1) additions!