我正在尝试编写一个简单的函数来检查数据库中是否存在用户名,如果是,则调用另一个函数来生成新的用户名。我的代码似乎已经失败了:
用户名功能: -
$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);
}
}
它似乎只是返回原始用户名。
答案 0 :(得分:1)
您可能需要稍微重新考虑一下代码。写下纸上的步骤;这有助于我。到目前为止,我可以看到:
因此,请在表单张贴时检查用户名:
<?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();
}
希望这会有所帮助。显然,在您的设置中需要进行一些修改,但这是您需要的一般流程。