I recently needed to generate username based on first and last name of Facebook and Google users. So I created PHP functions that achieve the results I wanted.
The function below simply combines the first and last name of the user, trims long names and adds a random number as suffix. So if I want to create a username from the name “Mike Tyson”, the result will be “mikentyso94” etc.
Creating unique username with MySqli
We now know how to generate a username, but what if the username already exist in the database, it can result in duplicates and script failures. So in next example, we generate the username, but we also check in the database for uniqueness.
That’s it, I hope it servers the purpose. If you want to improve this PHP code, please do so by commenting in comment section.