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

前端 未结 8 1897
醉话见心
醉话见心 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:09

    I would use something like this:

    // the username
    $username = "foo";
    
    // find all users like foo%
    $q = mysql_query("SELECT * FROM users WHERE username LIKE '".$username."%' ORDER BY id DESC");
    
    // no users
    if (mysql_num_rows($q) == 0) {
        // create $username
    }
    else {
    
        $last_num = 0;
    
        // find all foo users
        while ($row = mysql_fetch_array($q)) {
    
            // match foo + number
            if (preg_match("/^".preg_quote($username)."+([0-9]+)$/i", $row['username'], $match)) {
    
                // extract the number part
                $num = (int) $match[1];
    
                // set the highest number
                if ($num > $last_num) $last_num = $num;
            }
        }
    
        // append the highest number to the username
        if ($last_num > 0) $username .= $last_num + 1;
    
        // create $username
    }
    

提交回复
热议问题