helloworld001 Posted February 22, 2015 Share Posted February 22, 2015 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? Quote Link to comment Share on other sites More sharing options...
Barand Posted February 23, 2015 Share Posted February 23, 2015 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. Quote Link to comment Share on other sites More sharing options...
tryingtolearn Posted February 23, 2015 Share Posted February 23, 2015 (edited) 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 February 23, 2015 by tryingtolearn Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.