{"id":2441,"date":"2018-09-04T17:58:56","date_gmt":"2018-09-04T12:28:56","guid":{"rendered":"https:\/\/pheonixsolutions.com\/blog\/?p=2441"},"modified":"2026-09-28T17:38:52","modified_gmt":"2026-09-28T12:08:52","slug":"generate-username-from-user-first-and-last-name-codeigniter-library","status":"publish","type":"post","link":"https:\/\/pheonixsolutions.com\/blog\/generate-username-from-user-first-and-last-name-codeigniter-library\/","title":{"rendered":"How to Generate a Unique Username from First and Last Name in CodeIgniter"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Post Date:<\/strong> September 4, 2018<br><strong>Last Updated:<\/strong> September 22, 2026<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Generating usernames automatically can simplify user registration and account creation workflows. In CodeIgniter, a custom library can be used to generate a username based on a user&#8217;s first and last name while checking the database to ensure that the generated username is unique.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this guide, we will create a reusable CodeIgniter library that generates a unique username from a user&#8217;s name and verifies its availability in the database.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Before proceeding, ensure you have:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A CodeIgniter application configured and running<\/li>\n\n\n\n<li>PHP installed and configured<\/li>\n\n\n\n<li>A database connection configured in CodeIgniter<\/li>\n\n\n\n<li>A <code>users<\/code> table containing a <code>username<\/code> column<\/li>\n\n\n\n<li>Basic knowledge of CodeIgniter libraries and controllers<\/li>\n<\/ul>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> The example below follows the CodeIgniter 3 library structure.<\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\">Implementation<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1: Create the Library<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Navigate to the CodeIgniter application libraries directory:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">application\/libraries\/\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Create a new PHP file named:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Unique_username_lib.php\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Step 2: Add the Custom Library Code<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Add the following code to <code>Unique_username_lib.php<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\n\ndefined('BASEPATH') OR exit('No direct script access allowed');\n\nclass Unique_username_lib\n{\n    protected $CI;\n\n    public function __construct()\n    {\n        $this->CI =&amp; get_instance();\n        $this->CI->load->database();\n    }\n\n    \/**\n     * Generate a unique username from the user's name.\n     *\/\n    public function generate_unique_username($string_name = '', $rand_no = '')\n    {\n        while (true) {\n\n            \/\/ Convert the name to lowercase and split it into parts.\n            $username_parts = array_filter(\n                explode(' ', strtolower(trim($string_name)))\n            );\n\n            \/\/ Use only the first two name parts.\n            $username_parts = array_slice($username_parts, 0, 2);\n\n            \/\/ Use up to 8 characters from the first name.\n            $part1 = !empty($username_parts[0])\n                ? substr($username_parts[0], 0, 8)\n                : '';\n\n            \/\/ Use up to 5 characters from the last name.\n            $part2 = !empty($username_parts[1])\n                ? substr($username_parts[1], 0, 5)\n                : '';\n\n            \/\/ Add a random number when configured.\n            $part3 = $rand_no\n                ? rand(0, $rand_no)\n                : '';\n\n            \/\/ Generate the username.\n            $username = $part1 . str_shuffle($part2) . $part3;\n\n            \/\/ Check whether the username already exists.\n            $username_exists = $this->username_exist_in_database($username);\n\n            if (!$username_exists) {\n                return $username;\n            }\n        }\n    }\n\n    \/**\n     * Check whether a username already exists.\n     *\/\n    public function username_exist_in_database($username = '')\n    {\n        $sql = \"SELECT username\n                FROM \" . DB_PREFIX . \"users\n                WHERE username = ?\";\n\n        $results = $this->CI->db->query($sql, array($username));\n\n        return $results->num_rows() > 0;\n    }\n}\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Step 3: Load the Library<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Load the custom library from your CodeIgniter controller:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$this->load->library('unique_username_lib');\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">CodeIgniter will load the library from:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">application\/libraries\/Unique_username_lib.php\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Step 4: Generate the Username<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">After loading the library, call the <code>generate_unique_username()<\/code> method from your controller.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$string_name = 'Pheonix Solutions';\n\n$username = $this->unique_username_lib->generate_unique_username(\n    $string_name,\n    9999\n);\n\necho $username;\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The generated username can contain a combination of the first name, part of the last name, and a random number.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">pheonixolutions1234\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The exact output will vary because the library uses <code>str_shuffle()<\/code> and a random number.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 5: Check Username Uniqueness<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The library checks the <code>users<\/code> table before returning a username.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The following query is used:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">SELECT username\nFROM users\nWHERE username = ?\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If the username already exists, the library generates another username and checks the database again.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If the username does not exist, it is returned to the controller.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Important Considerations<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Database Prefix<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The example uses:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">DB_PREFIX\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Make sure <code>DB_PREFIX<\/code> is defined correctly in your CodeIgniter application.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If your application does not use a database prefix, you can reference the table directly:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">FROM users\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Add a Unique Database Constraint<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Application-level checks should not be the only protection against duplicate usernames.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is recommended to add a unique constraint to the database column:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">ALTER TABLE users\nADD UNIQUE KEY unique_username (username);\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This provides database-level protection against duplicate usernames, including situations where multiple requests attempt to create the same username at the same time.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Validate User Input<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Always validate and sanitize the name before generating a username. User-provided input should not be trusted directly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$string_name = trim($string_name);\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Additional validation can be implemented based on the requirements of the application.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Troubleshooting<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Library Not Found<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If CodeIgniter reports that the library cannot be found, verify the file location and name:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">application\/libraries\/Unique_username_lib.php\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Also ensure that the class name matches the library:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Unique_username_lib\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Duplicate Usernames<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If duplicate usernames are being generated, verify that:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The database query is checking the correct table.<\/li>\n\n\n\n<li>The <code>username<\/code> column contains the correct values.<\/li>\n\n\n\n<li>The database has a unique constraint on the username column.<\/li>\n\n\n\n<li>Concurrent requests are handled using appropriate database constraints.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Database Connection Error<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Verify that the database configuration is correctly defined in your CodeIgniter application and that the database server is accessible.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A custom CodeIgniter library provides a reusable way to generate usernames automatically from user names.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By combining name-based username generation with a database availability check, applications can create readable usernames while reducing the possibility of duplicates.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For production applications, database-level uniqueness should also be enforced to ensure reliable username management.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently Asked Questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1. Can this library generate usernames from a single name?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. If only one name is provided, the library can generate a username using the available name component and optional random number.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2. How does the library prevent duplicate usernames?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The generated username is checked against the <code>users<\/code> table. If it already exists, another username is generated.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3. Should username uniqueness be enforced in the database?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. A unique database constraint is recommended as an additional safeguard against duplicate usernames.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">4. Can the username format be customized?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. You can modify the <code>generate_unique_username()<\/code> method to change the number of characters, separators, prefixes, suffixes, or random values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">5. Does this example work with CodeIgniter 4?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This example follows the CodeIgniter 3 library structure. CodeIgniter 4 uses a different application structure and library\/service-loading approach, so the implementation should be adapted accordingly.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related Articles<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/pheonixsolutions.com\/blog\/how-to-add-google-recaptcha-in-php-codeigniter\/\">How to add Google ReCAPTCHA in PHP Codeigniter<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/pheonixsolutions.com\/blog\/how-to-debug-in-codeigniter\/\">How to debug in Codeigniter<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Talk to our experts<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Have a technology challenge or looking for the right solution for your business? Our team can help you with <strong>cloud, DevOps, development, infrastructure, design, and more<\/strong>. Feel free to reach out to our experts <a href=\"https:\/\/pheonixsolutions.com\/contact\">here<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Post Date: September 4, 2018Last Updated: September 22, 2026 Introduction Generating usernames automatically can simplify user registration and account creation [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[1022],"tags":[341,273],"class_list":["post-2441","post","type-post","status-publish","format-standard","hentry","category-web-architecture","tag-codeigniter","tag-php","psol-cat-web-architecture"],"jetpack_publicize_connections":[],"jetpack_shortlink":"https:\/\/wp.me\/phn2x7-Dn","jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts\/2441","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/comments?post=2441"}],"version-history":[{"count":2,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts\/2441\/revisions"}],"predecessor-version":[{"id":11960,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts\/2441\/revisions\/11960"}],"wp:attachment":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/media?parent=2441"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/categories?post=2441"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/tags?post=2441"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}