0

我有以下递归函数,如果它必须循环一次,它不会返回任何东西。我可以在返回条件中回显用户名,它会在循环后显示正确的用户名,并附加一个数字(例如 jdoe_45),但它不会返回它。

function createUsername ($conn, $firstname, $lastname, $numerate = false) {

    $fn = preg_replace("/[^A-Za-z0-9 ]/", '', $firstname);
    $ln = preg_replace("/[^A-Za-z0-9 ]/", '', $lastname);

    $arg = ($numerate) ? '_' . rand(11, 99) : '';

    $username = strtolower(substr($fn, 0, 1) . $ln . $arg);

    $sql = "SELECT * FROM users WHERE username = '$username'";
    $rs  = mysql_query($sql, $conn) or die ("Could not execute query.");
    $num = mysql_numrows($rs);

    if ($num == 0) {

        return $username;
    }

    createUsername($conn, $firstname, $lastname, 1);
}
4

2 回答 2

0

您忘记获取结果:

if ($num == 0) {
    $row = mysql_fetch($rs);
    $username = $row['username'];
    return $username;
}
于 2013-01-16T02:06:04.873 回答
0

您还需要返回递归调用:

return createUsername($conn, $firstname, $lastname, 1);

目前,您仅在$num == 0.

于 2013-01-16T02:08:07.917 回答