Sideshow
Sideshow

Reputation: 1351

check if username exists and generate new username if it does PHP

I am trying to write a simple function that checks if a username exists in the db and if so to call another function to generate a new username. My code seems to fall over though:

Username Function:-

$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 Username Function:

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);
}
}

It just seems to return the original username.

Upvotes: 0

Views: 725

Answers (1)

Martin Bean
Martin Bean

Reputation: 39399

You probably need to re-factor your code a little. Write out the steps on paper; that helps me. So far, I can see:

  1. You want to check a username is unique on form submission
  2. If it's not, generate a new username

So, check the username when your form is POSTed:

<?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?
        }
    }

And then write your functions:

<?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();
    }

Hopefully this will help. Obviously it'll need some modification to work in your set-up, but this is the general flow you'll need.

Upvotes: 1

Related Questions