Post Date: September 4, 2018
Last Updated: September 22, 2026
Introduction
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’s first and last name while checking the database to ensure that the generated username is unique.
In this guide, we will create a reusable CodeIgniter library that generates a unique username from a user’s name and verifies its availability in the database.
Prerequisites
Before proceeding, ensure you have:
- A CodeIgniter application configured and running
- PHP installed and configured
- A database connection configured in CodeIgniter
- A
userstable containing ausernamecolumn - Basic knowledge of CodeIgniter libraries and controllers
Note: The example below follows the CodeIgniter 3 library structure.
Implementation
Step 1: Create the Library
Navigate to the CodeIgniter application libraries directory:
application/libraries/
Create a new PHP file named:
Unique_username_lib.php
Step 2: Add the Custom Library Code
Add the following code to Unique_username_lib.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Unique_username_lib
{
protected $CI;
public function __construct()
{
$this->CI =& get_instance();
$this->CI->load->database();
}
/**
* Generate a unique username from the user's name.
*/
public function generate_unique_username($string_name = '', $rand_no = '')
{
while (true) {
// Convert the name to lowercase and split it into parts.
$username_parts = array_filter(
explode(' ', strtolower(trim($string_name)))
);
// Use only the first two name parts.
$username_parts = array_slice($username_parts, 0, 2);
// Use up to 8 characters from the first name.
$part1 = !empty($username_parts[0])
? substr($username_parts[0], 0, 8)
: '';
// Use up to 5 characters from the last name.
$part2 = !empty($username_parts[1])
? substr($username_parts[1], 0, 5)
: '';
// Add a random number when configured.
$part3 = $rand_no
? rand(0, $rand_no)
: '';
// Generate the username.
$username = $part1 . str_shuffle($part2) . $part3;
// Check whether the username already exists.
$username_exists = $this->username_exist_in_database($username);
if (!$username_exists) {
return $username;
}
}
}
/**
* Check whether a username already exists.
*/
public function username_exist_in_database($username = '')
{
$sql = "SELECT username
FROM " . DB_PREFIX . "users
WHERE username = ?";
$results = $this->CI->db->query($sql, array($username));
return $results->num_rows() > 0;
}
}
Step 3: Load the Library
Load the custom library from your CodeIgniter controller:
$this->load->library('unique_username_lib');
CodeIgniter will load the library from:
application/libraries/Unique_username_lib.php
Step 4: Generate the Username
After loading the library, call the generate_unique_username() method from your controller.
For example:
$string_name = 'Pheonix Solutions';
$username = $this->unique_username_lib->generate_unique_username(
$string_name,
9999
);
echo $username;
The generated username can contain a combination of the first name, part of the last name, and a random number.
For example:
pheonixolutions1234
The exact output will vary because the library uses str_shuffle() and a random number.
Step 5: Check Username Uniqueness
The library checks the users table before returning a username.
The following query is used:
SELECT username FROM users WHERE username = ?
If the username already exists, the library generates another username and checks the database again.
If the username does not exist, it is returned to the controller.
Important Considerations
Database Prefix
The example uses:
DB_PREFIX
Make sure DB_PREFIX is defined correctly in your CodeIgniter application.
If your application does not use a database prefix, you can reference the table directly:
FROM users
Add a Unique Database Constraint
Application-level checks should not be the only protection against duplicate usernames.
It is recommended to add a unique constraint to the database column:
ALTER TABLE users ADD UNIQUE KEY unique_username (username);
This provides database-level protection against duplicate usernames, including situations where multiple requests attempt to create the same username at the same time.
Validate User Input
Always validate and sanitize the name before generating a username. User-provided input should not be trusted directly.
For example:
$string_name = trim($string_name);
Additional validation can be implemented based on the requirements of the application.
Troubleshooting
Library Not Found
If CodeIgniter reports that the library cannot be found, verify the file location and name:
application/libraries/Unique_username_lib.php
Also ensure that the class name matches the library:
class Unique_username_lib
Duplicate Usernames
If duplicate usernames are being generated, verify that:
- The database query is checking the correct table.
- The
usernamecolumn contains the correct values. - The database has a unique constraint on the username column.
- Concurrent requests are handled using appropriate database constraints.
Database Connection Error
Verify that the database configuration is correctly defined in your CodeIgniter application and that the database server is accessible.
Conclusion
A custom CodeIgniter library provides a reusable way to generate usernames automatically from user names.
By combining name-based username generation with a database availability check, applications can create readable usernames while reducing the possibility of duplicates.
For production applications, database-level uniqueness should also be enforced to ensure reliable username management.
Frequently Asked Questions
1. Can this library generate usernames from a single name?
Yes. If only one name is provided, the library can generate a username using the available name component and optional random number.
2. How does the library prevent duplicate usernames?
The generated username is checked against the users table. If it already exists, another username is generated.
3. Should username uniqueness be enforced in the database?
Yes. A unique database constraint is recommended as an additional safeguard against duplicate usernames.
4. Can the username format be customized?
Yes. You can modify the generate_unique_username() method to change the number of characters, separators, prefixes, suffixes, or random values.
5. Does this example work with CodeIgniter 4?
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.
Related Articles
Talk to our experts
Have a technology challenge or looking for the right solution for your business? Our team can help you with cloud, DevOps, development, infrastructure, design, and more. Feel free to reach out to our experts here.