dongying3830 2013-03-08 13:43
浏览 44
已采纳

递归PHP函数未返回预期值

I am trying to create a function that will create a unique username for each user stored in the database.

My plan was to create a username by concatenating the first and last name then check if this username was taken. If it wasn't just store it in the database and if it was then add a number on the end of it.

For example if ConnorAtherton was taken the function would next check ConnorAtherton1, ConnorAtherton2 until it found a unique username.

Here is the function (I have added some echo statements for debugging)

    function createUserName($username, $counter){

        global $fname, $lname;

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

        // 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 . "
";

            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 . "

";

            return $username;
    }

Here is what it returns to the console

    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

It returns the correct value after the loop (ConnorAtherton2) to begin with but I don't know why there would be a second value after the loop.

It returns ConnorAtherton1 and I need it to return ConnorAtherton2.

Any help is greatly appreciated.

  • 写回答

2条回答 默认 最新

  • doutian3269 2013-03-08 13:47
    关注

    The code executes as expected. What you are seeing is just the stack unwinding from the recursive calls.

    You should modify your function to exit after the recursive call, by returning the result from the recursive call

         //...
        $counter++;
        return createUserName($username, $counter);
     }
     //... Rest of fn omitted
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)