Jump to content

Username Increment


DavidY

Recommended Posts

I'm wanting to increment usernames which are to be alphabetic characters a-z and if someone uses "abc" it will automatically be given "abc1" and the next applicant to apply for that same username will automatically be given "abc2", the next "abc3" and so on. Can anybody help?

Link to comment
Share on other sites

When a user registers, just query the database for that username. If no results are found, give them the name. If results are found you can add a number to the username based on how many records were returned. You can use mysql_num_rows() to determine that.

Link to comment
Share on other sites

When a user registers, just query the database for that username. If no results are found, give them the name. If results are found you can add a number to the username based on how many records were returned. You can use mysql_num_rows() to determine that.
Thank you jkloth for your response. Can you provide some coding for the registration? I am starting with coding I've obtained from http://evolt.org/article/comment/17/60265/index.html which is quite old and wonder if there has been some more recent updates. I guess your sentence "If no results are found, give them the name." you mean "If no results are found, give them the name AND THE NUMBER 1 (example abc1). But then if abc was queried subsequent times it wouldn't be found because the username(s) with the numbers exist. Or maybe the usernames consists of two parts. I must admit I am fairly green but do believe the idea I have will avoid a new entrant to the site from having to think about a username that does not exist.
Link to comment
Share on other sites

Thank you jkloth for your response. Can you provide some coding for the registration? I am starting with coding I've obtained from http://evolt.org/article/comment/17/60265/index.html which is quite old and wonder if there has been some more recent updates.
Well, I've never written anything like that. I'm not sure how that would be written. If you wanted to post the code I'm sure others here can help you get that part working.
I guess your sentence "If no results are found, give them the name." you mean "If no results are found, give them the name AND THE NUMBER 1 (example abc1). But then if abc was queried subsequent times it wouldn't be found because the username(s) with the numbers exist. Or maybe the usernames consists of two parts. I must admit I am fairly green but do believe the idea I have will avoid a new entrant to the site from having to think about a username that does not exist.
As for querying the database, you would use the LIKE keyword in your query to see if the username exists. For example:SELECT * FROM users WHERE users.username LIKE 'abc%'That query will return all usernames that start with 'abc' so it would return names like abc1, abc2, abc3, etc. It would also return names like abc1231 and abcdef1 so there would likely be some extra filtering of the results in PHP to determine if a username exists. Or you could separate the username and number with a special character such as '_' so that you can always compare the username. Your query would then look like this:SELECT * FROM users WHERE users.username LIKE 'abc_%'So that will return usernames like abc_1, abc_2, etc. but omit names like abc123_1 and abcdef_1. Does that make sense?
Link to comment
Share on other sites

Yes. I'm not sure why.BTW, are we using the _ as a wildcard or a literal? I suppose it will match a literal '_' , but it should also match ANY single character. So 'abc_12' will match 'abc_12' AND 'abcd12'. That might cause a problem.

Link to comment
Share on other sites

Yes. I'm not sure why.BTW, are we using the _ as a wildcard or a literal? I suppose it will match a literal '_' , but it should also match ANY single character. So 'abc_12' will match 'abc_12' AND 'abcd12'. That might cause a problem.
I was actually using it as a literal. I'm not too familiar with SQL, so I didn't realize it was a wildcard character. In that case a '-' might work instead.
Link to comment
Share on other sites

I was actually using it as a literal. I'm not too familiar with SQL, so I didn't realize it was a wildcard character. In that case a '-' might work instead.
Thanks jkloth & Deirdre's Dad for your input. I'll work on those codes and come back in the next few days. The other matter I'd need to achieve is that I intend having 2 types of members, 1 using lower case and the other using capitals in their usernames and neither to use non-alphanumerical symbols such as .,":[]()&%$#@* can either one of you tell me how I can restrict the username charactors to a-z and A-Z?
Link to comment
Share on other sites

Welcome to regular expressions. We'll just write a simple func for that.

function notValidName ($name) {   $regex = '/[^a-zA-Z]/';   return preg_match($regex, $name);}

preg_match returns a Boolean value: true if the string matches the pattern, false if it doesn't. In this case, we try to match the [a-zA-Z] character classes. But that won't work directly. If the first character of the string matches, the expression returns true and never evaluates any other characters. So "Hi" returns true and 'H*' returns true. Not what you want. Instead, we NOT the whole character class with the ^ character. Now, the function evaluates every character until it finds one that is NOT a member of [a-bA-Z]. If it finds one, it returns true. If not, false. That is why the function is called notValidName. Use it like this:

if (notValidName ($str) ) {   // do something}

The alternative is to create a list of excluded characters and attempt to match them directly, but that is a big headache, and inefficient besides.This isn't much of an explanation of regular expressions. Google for more. There's a lot of stuff out there.

Link to comment
Share on other sites

Welcome to regular expressions. We'll just write a simple func for that.
function notValidName ($name) {   $regex = '/[^a-zA-Z]/';   return preg_match($regex, $name);}

preg_match returns a Boolean value: true if the string matches the pattern, false if it doesn't. In this case, we try to match the [a-zA-Z] character classes. But that won't work directly. If the first character of the string matches, the expression returns true and never evaluates any other characters. So "Hi" returns true and 'H*' returns true. Not what you want. Instead, we NOT the whole character class with the ^ character. Now, the function evaluates every character until it finds one that is NOT a member of [a-bA-Z]. If it finds one, it returns true. If not, false. That is why the function is called notValidName. Use it like this:

if (notValidName ($str) ) {   // do something}

The alternative is to create a list of excluded characters and attempt to match them directly, but that is a big headache, and inefficient besides.This isn't much of an explanation of regular expressions. Google for more. There's a lot of stuff out there.

Thank you. I intend having two types of membership meaning I'll use [a-z] for one type and [A-Z] for the other type but I think I can work out from the information you have provided how to achieve that.However, is there any way for the box where the username is printed to not accept non acceptable charactors for example if a member who is to be required to enter only lower case actually entered say "Shift+A" then only "a" would appear in other words "Shift" has no effect and if entered "Shift+8" neither "*" nor "8" would appear in other words nothing would appear? If I could achieve that then it would save a lot of error messages and subsequent attempts.Another problem I foresee is if say user abc2 wants to change the username to say xyz and receives xyz1 then after that occurs if another member applies with abc and already abc1 & abc3 is in existance I'd want that member to be given abc4 and not the vacant abc2 in other words once a username and number has been allocated then it remains with that user despite that user having a new or subsequent usernames.I'd also need to work out how to allow usernames to be changed with the old username left in the background, can you guide me in that direction?
Link to comment
Share on other sites

That first one's a pretty tall order. We have to test a lot of junk to find out what character has been entered. And it probably did not occur to you that users will be upset if they cannot use arrow keys for editing. I've also let the return key pass in case you want users to trigger a submit when they hit the return key (normal behavior). Anyway, the code below will screen for editing keys and lowercase. Replace "my_input_id" with the id of the input you really want to use. Actually, I suggest testing this in a separate document till you understand it. Play around with the variables so you'll know how to accept other keys as well.BTW, I use a couple coding tricks in here, and I'm also allowing for different browsers. If you want something explained, ask.

function accept_lowercase_only (e) {   e = e || window.event;   var uppercase = e.shiftKey;   var k = e.keyCode || e.which;   var editing = (k == 37 || k == 39 || k == 13);   var myKey = String.fromCharCode(k).toLowerCase();   var re = /[^a-z]/;   if (!editing && (uppercase || myKey.match(re) ) ) {	  return false;   }   return true;}function init () {   document.getElementById("my_input_id").onkeydown = accept_lowercase_only;}window.onload = init;

Link to comment
Share on other sites

That first one's a pretty tall order. We have to test a lot of junk to find out what character has been entered. And it probably did not occur to you that users will be upset if they cannot use arrow keys for editing. I've also let the return key pass in case you want users to trigger a submit when they hit the return key (normal behavior). Anyway, the code below will screen for editing keys and lowercase. Replace "my_input_id" with the id of the input you really want to use. Actually, I suggest testing this in a separate document till you understand it. Play around with the variables so you'll know how to accept other keys as well.BTW, I use a couple coding tricks in here, and I'm also allowing for different browsers. If you want something explained, ask.
function accept_lowercase_only (e) {   e = e || window.event;   var uppercase = e.shiftKey;   var k = e.keyCode || e.which;   var editing = (k == 37 || k == 39 || k == 13);   var myKey = String.fromCharCode(k).toLowerCase();   var re = /[^a-z]/;   if (!editing && (uppercase || myKey.match(re) ) ) {	  return false;   }   return true;}function init () {   document.getElementById("my_input_id").onkeydown = accept_lowercase_only;}window.onload = init;

Thank you. I don't understand much yet but as you suggested I'll play around with it. Have you any ideas of the 2nd part of my query?
Link to comment
Share on other sites

The query we discussed above should return all users with usernames 'abc' + number. Assign the usernames to an array as they come up. Then use natsort on the array. To keep with your example, the last item in the resulting array will be 'abc3'. From that you can extract the number and increment it by 1 to create the next userid. (Read about natsort to see why it is the better sorting algorithm.)If you want to keep a record of only the most recent usernames, then simply create a field for it. Update it every time someone changes a username. If you want a complete history of usernames, you create a field of type TEXT (65535 characters should handle one user's history) and store all the historical names as a comma-delimited string. preg_match and a simple regex will tell you if a name has been used before.That's assuming you want to keep the historical names associated with the original users. If the point is that any name ever used by anyone becomes an illegal name for the future, no matter who wants to use it, then it might be more efficient to create a separate table that has a single field: illegal names.I speak of efficiency in the abstract. If you expect only a few hundred DB queries a day, and only a few thousand users, then either technique is likely to seem as fast as another.

Link to comment
Share on other sites

The query we discussed above should return all users with usernames 'abc' + number. Assign the usernames to an array as they come up. Then use natsort on the array. To keep with your example, the last item in the resulting array will be 'abc3'. From that you can extract the number and increment it by 1 to create the next userid. (Read about natsort to see why it is the better sorting algorithm.)If you want to keep a record of only the most recent usernames, then simply create a field for it. Update it every time someone changes a username. If you want a complete history of usernames, you create a field of type TEXT (65535 characters should handle one user's history) and store all the historical names as a comma-delimited string. preg_match and a simple regex will tell you if a name has been used before.That's assuming you want to keep the historical names associated with the original users. If the point is that any name ever used by anyone becomes an illegal name for the future, no matter who wants to use it, then it might be more efficient to create a separate table that has a single field: illegal names.I speak of efficiency in the abstract. If you expect only a few hundred DB queries a day, and only a few thousand users, then either technique is likely to seem as fast as another.
Thank you. The website idea I have may develop far more than a few hundred queries a day and far more than a few thousand users so I gotta think big.
Link to comment
Share on other sites

  • 2 weeks later...
Thank you. I don't understand much yet but as you suggested I'll play around with it. Have you any ideas of the 2nd part of my query?
I've played around with your code by coming up with the script below but it does not work. The window opens OK but I'm able to insert any character with no restriction. The maxlength="30" restriction works OK and I wonder if the character restriction should be inserted somewhere close to that. I am playing around in the dark and have no idea what I should be doing so I'll need explicit guidance.<?function accept_lowercase_only (e) { e = e || window.event; var uppercase = e.shiftKey; var k = e.keyCode || e.which; var editing = (k == 37 || k == 39 || k == 13); var myKey = String.fromCharCode(k).toLowerCase(); var re = /[^a-z]/; if (!editing && (uppercase || myKey.match(re) ) ) { return false; } return true;}function init () { document.getElementById("user").onkeydown = accept_lowercase_only;window.onload = init;?><html><title>Registration Page</title><body><h1>Register</h1><form action="<?php echo $HTTP_SERVER_VARS['PHP_SELF']; ?>" method="post"><table align="left" border="0" cellspacing="0" cellpadding="3"><tr><td>Username:</td><td><input type="text" name="user" maxlength="30"></td></tr><tr><td colspan="2" align="right"><input type="submit" name="subjoin" value="JOIN"></td></tr></table></form></body></html><?}?>
Link to comment
Share on other sites

document.getElementById("user") requires an element with an ID attribute set to "user". Your input only has a name attribute. You need the name attribute for your form submission, but you also need the ID for JavaScript. Different attributes for different purposes. You still might have problems with my code :) but so far it isn't even running.Are you testing in Firefox? Your error console should have shown you part of the problem when it executed this line.

Link to comment
Share on other sites

<?function accept_lowercase_only (e) {   e = e || window.event;   var uppercase = e.shiftKey;   var k = e.keyCode || e.which;   var editing = (k == 37 || k == 39 || k == 13);   var myKey = String.fromCharCode(k).toLowerCase();   var re = /[^a-z]/;   if (!editing && (uppercase || myKey.match(re) ) ) {      return false;   }   return true;}function init () {   document.getElementById("user").onkeydown = accept_lowercase_only;window.onload = init;?><html><title>Registration Page</title><body><h1>Register</h1><form action="<?php echo $HTTP_SERVER_VARS['PHP_SELF']; ?>" method="post"><table align="left" border="0" cellspacing="0" cellpadding="3"><tr><td>Username:</td><td><input type="text" name="user" maxlength="30"></td></tr><tr><td colspan="2" align="right"><input type="submit" name="subjoin" value="JOIN"></td></tr></table></form></body></html><?}?>

Is that the exact code that you have? If it is you have a few issues. First of all, the code DD provided you is JavaScript, not PHP. It needs to go between <script> tags in the head of your document (which you currently are missing). Secondly the last curly brace '}' should go after the document.getElementById("user") line:function init () { document.getElementById("user").onkeydown = accept_lowercase_only;}
Link to comment
Share on other sites

Wow, I didn't even see the PHP tags. I switched environments because of this request from OP:

However, is there any way for the box where the username is printed to not accept non acceptable charactors
I suppose I assumed OP knew that capturing the input while the document was still in the browser would mean JavaScript. Sorry if I did not make that clear.
Link to comment
Share on other sites

Is that the exact code that you have? If it is you have a few issues. First of all, the code DD provided you is JavaScript, not PHP. It needs to go between <script> tags in the head of your document (which you currently are missing). Secondly the last curly brace '}' should go after the document.getElementById("user") line:function init () { document.getElementById("user").onkeydown = accept_lowercase_only;}
Thank you both for your input. I'll first answer the questions. I'm testing in Explorer. The code I submitted part came from DD and the html came from a portion of the register.php file I got from http://evolt.org/article/comment/17/60265/index.html and I deleted the password line. It was my idea of shifting the curly brace from where it should be, to inside the little piece of PHP at the bottom so that the coding embraced the html. The "exact code" I intend using will come from the evolt site, however I took DD's advise of testing on a separate document so I first got the html coding to work with only a username box, on the separate document then tried to add the coding DD provided just to see if the box would accept the "not wanted" characters. I tried searching the html site for a character restriction and could not find any, but that was a couple of years ago, there maybe an update. I think a html restriction would be better, the same as maxlength "30" restriction. However, I know absolutely nothing about Javascript and only a little about PHP, so if the restriction must be one or the other I'll need coding in PHP. Any ideas?
Link to comment
Share on other sites

You can't prevent users from entering illegal characters using PHP. You can only validate the username and if it has illegal characters, reject it and send the user to an error page or to the registration page (or wherever they are entering the username) with an error message.If you want to prevent illegal characters from being entered into the text box at all you need to use JavaScript. That's the only way.

Link to comment
Share on other sites

Really, a good app should do both. You always want to validate data at the server so that you are 100% certain you have the right stuff. But users also like it a lot when you validate data immediately, with JavaScript. Waiting several (or many) seconds just to find out you made a mistake is very frustrating. A JavaScript solution gives immediate feedback. I'm sure you've seen it used many times, probably every time you open an account, login somewhere, or order something on line.

Link to comment
Share on other sites

Really, a good app should do both. You always want to validate data at the server so that you are 100% certain you have the right stuff. But users also like it a lot when you validate data immediately, with JavaScript. Waiting several (or many) seconds just to find out you made a mistake is very frustrating. A JavaScript solution gives immediate feedback. I'm sure you've seen it used many times, probably every time you open an account, login somewhere, or order something on line.
I've now got it working using the script below;<html><title>Registration Page</title><body><script>function accept_lowercase_only (e) { e = e || window.event; var uppercase = e.shiftKey; var k = e.keyCode || e.which; var editing = (k == 8 || k == 13 || k == 37 || k == 39); var myKey = String.fromCharCode(k).toLowerCase(); var re = /[^a-z]/; if (!editing && (uppercase || myKey.match(re) ) ) { return false; } return true;}function init () { document.getElementById("user").onkeydown = accept_lowercase_only;}window.onload = init;</script><h1>Register1</h1><form action="<?php echo $HTTP_SERVER_VARS['PHP_SELF']; ?>" method="post"><table align="left" border="0" cellspacing="0" cellpadding="3"><tr><td>Username:</td><td><input type="text" name="user" maxlength="30"></td></tr><tr><td>Password:</td><td><input type="password" name="pass" maxlength="30"></td></tr><tr><td colspan="2" align="right"><input type="submit" name="subjoin" value="JOIN"></td></tr></table></form></body></html>EXCEPT if I press Caps Lock it allows uppercase. Can you provide the code to malfunction the Caps Lock? I also managed to work out how to allow the Backspace to work by inserting "k == 8" and I've learned the 13 is the carriage return but can only guess the 37 & 39 are the left and right arrows but I can't find those number in the ascii code, can you tell me how you arrived at those numbers?I am now working on the other type of user which is to have uppercase A-Z and also to allow ( ) $ @ & ' - . The first 5 symbols are normally obtainable by pressing the Shift key but the last 3 are normally obtainable without the Shift key which is confusing me and I can't yet get it to work, despite reversing the applicable pieces of code you provide earlier. Can you provide the Javascript code for that please and with the malfunction of the Caps Lock?
Link to comment
Share on other sites

I wouldn't try and disable keys or buttons. You can use string methods to take all captured text and convert it to lowercase.

Link to comment
Share on other sites

I wouldn't try and disable keys or buttons. You can use string methods to take all captured text and convert it to lowercase.
Can you tell me how to use string methods to take all captured text and convert it to lower case? I also need to learn how to convert to uppercase plus allow for those other 8 characters.Can you tell me why you wouldn't disable keys or buttons?I can foresee the unwanted characters being used if the user is using a browser that is not compatible with Javascript so I will also need to be able to get PHP to reject the unwanted characters. The reason why I prefer to have characters disabled is that the user would in normal situations make only one attempt to register and they would not receive any rejections.Another thought I've had, is there a way to reject potential users if they are NOT using Explorer as their browser?
Link to comment
Share on other sites

Archived

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

×
×
  • Create New...