0

我正在尝试编写一个简单的函数来检查数据库中是否存在用户名,如果存在则调用另一个函数来生成新的用户名。我的代码似乎失败了:

用户名功能:-

$user1=create_username($fname, $company);

function create_username($surname, $company){

//$name_method=str_replace(" ", "", $surname);
$name_method=$surname.$forename;
$company_name_method=str_replace(" ", "", $company);


if(strlen($name_method)<=5)
{
    $addition=rand(11,99);
    $first=$addition.$name_method;
}
else
{
    $first=substr($name_method,0,5);
}
if(strlen($company_name_method)<=5)
{
    $addition2=rand(11,99);
    $second=$addition2.$company_name_method;
}
else
{
    $second=substr($company_name_method,0,5);
}
$middle=rand(100,1000);

$username=$first.$middle.$second;
return($username);
}

检查用户名功能:

check_user($user1, $dbc, $fname, $company);

function check_user($user1, $dbc, $surname, $company){
$check_username="SELECT username FROM is_user_db WHERE username='$user1'";
$resultx=mysqli_query($dbc, $check_username) or die("Could not check username");
$num_rows=mysqli_num_rows($resultx);
if($num_rows>0)
{
    $user1=create_username($fname, $company);
    check_user($user1, $dbc, $fname, $company);

}
else
{
    return($user1);
}
}

它似乎只是返回原始用户名。

4

1 回答 1

1

您可能需要稍微重构您的代码。在纸上写下步骤;这对我有帮助。到目前为止,我可以看到:

  1. 您想检查用户名在表单提交时是否唯一
  2. 如果不是,生成一个新的用户名

因此,请在发布表单时检查用户名:

<?php
    if (isset($_POST['submit'])) {
        if (username_unique($_POST['username'])) {
            // carry on processing form
        }
        else {
            $suggested_username = suggest_username($_POST['username']);
            // display form, with new suggested username?
        }
    }

然后编写你的函数:

<?php
    // following on from code from above

    function check_username($username) {
        // get database connection (I use PDO)
        $sql = "SELECT COUNT(*) AS count FROM users_tbl WHERE username = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array($username));
        $row = $stmt->fetchObject();
        return ($row->count > 0); // if 'count' is more than 0, username already exists
    }

    function suggest_username($username) {
        // take username, and add some random letters and numbers on the end
        return $username . uniqid();
    }

希望这会有所帮助。显然,它需要一些修改才能在您的设置中工作,但这是您需要的一般流程。

于 2012-07-23T11:03:17.507 回答