Jump to content

Quick question. How can I increment a unique username variable?


helloworld001

Recommended Posts

I have a register form where a user enters a full name, email and password.  I do not want to give them the option of choosing their own "username"; rather I want to automatically create the username  from their "full name". 

 

So far I can create the username by removing space and symbols from full name. Like this.

$fullname	 = 	trim($_GET['fullname']);
$username	 = 	preg_replace('/\s+/', '', $fullname);

Looking at that, John Smith would become "johnsmith".

 

Since there could be dozens of people with the name "john smith", I was thinking of assigning unique number to each of them. Like this "johnsmith1", "johnsmith2", "johnsmith3"..etc.  How would you say I go on incrementing the username like that?

You could run a query to count the jonsmiths

SELECT COUNT(*) as count FROM user WHERE username LIKE 'johnsmith%'

Append the returned count to the username, so first gets johnsmith, second gets johnsmith1 etc

 

In addition, add a UNIQUE constraint to the username column. In the event two johnsmiths register simultaneously you will then get an error, in which case repeat the process.

Well that seems  a heck of alot quicker than what I was thinking

(also assuming that the uniqueName column is set to unique)

<?php
try {
    // Create the object:
    $pdo = new PDO('mysql:dbnameYOURDBNAMEHERE;host=localhost', 'USERNAMEHERE', 'PASSWORDHERE');
} catch (PDOException $e) {
    print_r($e->getMessage());
}
function uName($pdo, $un){
    global $id;
    $q = 'INSERT INTO uun (uniqueName) VALUES (:un)';
    $stmt = $pdo->prepare($q);
    if($stmt->execute(array(':un' => $un))){
        $id = $pdo->lastInsertId();
    }
    return $id;
}
$id = NULL;
$x = NULL; 
while(is_null($id)) {
    $unn = "JohnDoe";
    uName($pdo, $unn.$x);
    $x++;
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.