0

我正在尝试创建一个函数,该函数将为存储在数据库中的每个用户创建一个唯一的用户名。

我的计划是通过连接名字和姓氏来创建一个用户名,然后检查是否使用了这个用户名。如果不只是将其存储在数据库中,并且如果是,则在其末尾添加一个数字。

例如,如果使用 ConnorAtherton,该函数接下来会检查 ConnorAtherton1、ConnorAtherton2,直到找到唯一的用户名。

这是函数(我添加了一些用于调试的回显语句)

    function createUserName($username, $counter){

        global $fname, $lname;

        echo "\t\t\tUsername at Start - " . $username . "\n";

        // connect to database
        require($_SERVER['DOCUMENT_ROOT'] . "/inc/db.connect.php");

        $stmt = $conn->prepare('SELECT * FROM users WHERE username = ?');
        $stmt->bind_param('s', $username); 
        $stmt->execute();
        $stmt->store_result();

        echo "\t\t\tUsername before loop - " . $username . "\n";

            if( $stmt->num_rows > 0){

                //construct original name and try again
                $username = ucfirst($fname) . ucfirst($lname) . $counter;
                $counter++;
                createUserName($username, $counter);

            }

            echo "\t\t\tUsername after loop - " . $username . "\n\n";

            return $username;
    }

这是它返回到控制台的内容

    Username at Start - ConnorAtherton
    Username before loop - ConnorAtherton
    Username at Start - ConnorAtherton1
    Username before loop - ConnorAtherton1
    Username at Start - ConnorAtherton2
    Username before loop - ConnorAtherton2
    Username after loop - ConnorAtherton2

    Username after loop - ConnorAtherton1

它在循环(ConnorAtherton2)开始后返回正确的值,但我不知道为什么循环后会有第二个值。

它返回 ConnorAtherton1,我需要它返回 ConnorAtherton2。

任何帮助是极大的赞赏。

4

2 回答 2

3

代码按预期执行。您所看到的只是从递归调用中展开的堆栈。

您应该通过返回递归调用的结果来修改函数以在递归调用后退出

     //...
    $counter++;
    return createUserName($username, $counter);
 }
 //... Rest of fn omitted
于 2013-03-08T13:47:55.087 回答
1

您可以在不使用递归的情况下更轻松地实现您想要的。基本逻辑如下所示:

$counter = '';
do {
    $username = ucfirst($fname) . ucfirst($lname) . ($counter++);
} while(!doesNameExist($username));

您只需要实现该doesNameExist()方法。true如果名称已经存在,您可以在那里进行数据库查询并返回。

($counter++)部分将在第一次迭代时附加一个空字符串(++后缀在评估值后增加变量)。

于 2013-03-08T13:54:27.263 回答