How do I put extra number at the end of username if duplicate

前端 未结 8 1889
醉话见心
醉话见心 2021-01-19 23:31

Hard to explain, and let me show an example.

  1. If username foo already exists in MySQL I want php script will allow it but to be foo1
8条回答
  •  一生所求
    2021-01-20 00:26

    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.

提交回复
热议问题