Ok so i wanted a script that when your registering on a website it would check and see if the name exists and if it does then it will autoincrement the name with a number on the end. Some problems i faced were link in these examples
existing names
fred
fred1
fred2
fred2012
so if someone types in fred it would not look at the last number it would instead give fred3 as available. if someone typed in fred1 it would recognise a number on the end and increment it to the next available.. once again fred3. I thought the code was brilliant, it looks valid to me, however it doesnt work
parts of it work like the finding of the number on the end and autoincrementing of it. however the do while loop that checks the new name against the database and redoes the autoincrement until it finds an empty spot to use doesnt work
PHP Code:
$username = $_POST['username']; //fred $query = "SELECT name FROM user WHERE name = '$username'"; $result = mysql_query($query, $dbConn) or die ( "Error in query: $query. " . mysql_error() ); $rows = mysql_num_rows($result); if($rows < 1) //no such user exists { echo $username." is free"; //fred is available die(); } $fnumber = $username; $secrows = 1; do { if (!is_numeric(substr($fnumber,-1))){$newname = $username."1";} //fred doesnt have a number so we give it fred1 else { //if fred does have a number ie fred1, fred5, fred34 do{ $fnumber = substr($fnumber,1);} while (!is_numeric($fnumber)); //removes all the letters untill it gets the numbers at the end ie 34 $newname = str_replace($fnumber,"",$username); //removes 34 from fred34 $fnumber++; //adds 1 to 35 making 35 $newname = $newname.$fnumber; //adds 35 to the end of fred making fred35 } $secquery = "SELECT name FROM user WHERE name = '$newname'"; $secresult = mysql_query($secquery, $dbConn) or die ( "Error in query: $query. " . mysql_error() ); $secrows = mysql_num_rows($secresult); //check and see if fred35 exists } while ($secrows == 1); //keep adding 1 until it finds a fredx that isnt taken echo $newname." is free";
Your code is only looking at the last character so any number after 9 would begin to give unexpected results. If the numbers will always be at the end you could cast the string to a integer and increment that, but that would give strange results if there were numbers elsewhere within the string.
actually its not looking at the last number. if you look it the second do what it does it is it strips away every letter from the start and each time tests to see if its left with a pure number. so anything after 10 work
DOH!!! never mind. found the problem. i set $fnumber up as the username at the start of that first loop. but then inside the loop i boil $fnumber down to a number. so when it goes to do the loop again its not right. so i did this
PHP Code:
$secrows = mysql_num_rows($secresult); //check and see if fred35 exists
$fnumber = $newname;
Bookmarks