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

前端 未结 8 1886
醉话见心
醉话见心 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
      $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";
      }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题