Skip to content
Advertisement

How can I add a number to value if already exist in CodeIgniter

In my register form I have an input which is unique but if more than two users would like to create an exact username I would like for the second username created to have a number after the typed value.

For example we have two users:

username 1: codelover

username 2: codelover2 and so on.

I currently have this in my controller:

    // Create Page Data Array
        $data = array(
            'first_name' => strip_tags($this->input->post('first_name')),
            'last_name'  => strip_tags($this->input->post('last_name')),
            'email'      => strip_tags($this->input->post('email')),
            //'username'   => strip_tags($this->input->post('username')),
            'ip_address' => $this->input->ip_address(),
            'genre'      => $this->input->post('genre'),
            'slug'       => $slug,
            'status'    =>  'active',
            /* 1-Founder, 2-Administrator, 3-Editor, 4-Author , 5-Contributor , 6-Subscriber , 7-Banned, 8-Suspended */
            'role'       => 'Subscriber',
            'password'   => strip_tags(password_hash($this->input->post('password'), PASSWORD_DEFAULT)),
            'password2'  => strip_tags(password_hash($this->input->post('password2'), PASSWORD_DEFAULT)),
        );
// Is this the right approach of doing this?
            $i = 0;
            while($this->input->post('username') != 0){
$i++;
                $data['username'] = strip_tags($this->input->post('username'.'.'.$i));
            }
            //Check if username and/or email already exist.
            $existent_username = $this->User_model->existent_username($this->input->post('username'));
            $existent_email = $this->User_model->existent_email($this->input->post('email'));
            
            if (!empty($existent_username) || ($existent_email)) {
                // Create Message
                $this->session->set_flashdata('error', 'Username and/or Email already exist. Try again.');              
                
                // Redirect to pages
                redirect('users/register');
            } else {
                // Add User
                $this->User_model->add($data);

and this in my model which checks if username already exists:

public function existent_username($username) {
    $query = $this->db->get_where($this->table, array('username' => $username));
    return $query->row_array();
}

This is what I’m trying to do but in CodeIgniter:

if(empty($existent_username)){
                    $query = mysqli_query($con, "SELECT username FROM users WHERE username = '$username'");

                    $i = 0;
                    // If username already exists, add number to username
                    while(mysqli_num_rows($query) != 0){
                        $i++;
                        $username = $username ."." . $i;
                        $query = mysqli_query($con, "SELECT username FROM users WHERE username = '$username'");
                    }
                }

Advertisement

Answer

First of all

// Is this the right approach of doing this?
$i = 0;
while($this->input->post('username') != 0) {
    $i++;
    $data['username'] = strip_tags($this->input->post('username'.'.'.$i));
}

This is wrong, its seems to me you are running an infinite loop here. I did not even understand why you need it. If you users can provide multiple username then get the input fields value first then run the loop.

Now about the main question, you should the get all the existing usernames thats partially matches with the provided username. then generate the username and check the username already existed or not. If not then that’s the username. like this.

$username = $this->input->post('username');
$existent_username = $this->User_model->existent_username($username));
if (!empty($existent_username)) {
    $partially_matched_usernames = $this->db->select('username')->like('username', $username, 'after')->from('users')->get()->result_array();
    $usernames_array = array_column($partially_matched_usernames, 'username');

    // now generate the username
    $i = 1;
    while(true) {
        if( ! in_array($username.$i, $usernames_array)) {
            $username = $username.$i;
            break;
        }
        $i++;
    }
    echo $username;
}

I did not run this code, so there could be any error. I think you will able to fix that by yourself.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement