drza10046 2017-04-05 13:42
浏览 265

如何生成唯一的用户名 - PHP

I have strings of usernames in array . I want to generate a unique string of username which do not exits in array.(probably with some numbers following the username)

How do I achieve this?

I have summarize the code:

function generate_unique_username(){
    $firstname      = "james";//data coming from user
    $lastname       = "oduro";//data coming from user
    $new_username   = $firstname.$lastname;
    $usersnames     = array("james39","oduro32","kwame93","elvisasante","frimpong32","edward32","jamesoduro");

    //Loop through ARRAY usernames and check elements against VAR $new_username

    if (in_array($new_username, $usersnames)) {
        //generate new username which is not inside array
        //the new generated string should also be check against array to ensure is doens not exit.


    }else{
        return $new_username;
    }
}

Thank you.

  • 写回答

1条回答 默认 最新

  • doufuxing8691 2017-11-24 12:31
    关注

    Generating username from the stored array is not a good practice, I would suggest you to use the database.

    If you are using the database instead of the array, you can use the best method to generate the unique username as following:

    function generate_unique_username(){
        $firstname      = "james";//data coming from user
        $lastname       = "oduro";//data coming from user
        $new_username   = $firstname.$lastname;
    
        /* Note: writing here pseudo sql code, replace with the actual php mysql query syntax */
        $query = "SELECT COUNT(id) as user_count FROM user WHERE username like '%".$new_username."%'";
        $result = mysql_query($query);
        $count = $result['user_count'];
    
        if(!empty($count)) {
            $new_username = $new_username . $count;
        }
    
        return $new_username;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探