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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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++;
}
?>
Edited by tryingtolearn
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.