Mark Alan
Mark Alan

Reputation: 455

if condition is not working properly it is not checking properly

I have created a function to create automatic username on the bassis of name if name already exist then username will be creted on the basis of user id but when I created a user and tested if the name is already not present into the database it is creating username alongwith user id as it shouldn't be because test name is not already in the database. here is my code

// $user_id is the last inserted id
$check_username = $this->db->where('name', $name);
        $check_username = $this->db->where('id !=', $user_id);
        $check_username = $this->db->get('users');

        if($check_username >= 1) {
            $username = strtolower(str_replace(" ", ".", $name)) . $user_id;
        } else {
            $username = strtolower(str_replace(" ", ".", $name));
        }

        $this->db->where('id', $user_id);
        $this->db->update('users', array("username" => $username));

Upvotes: 0

Views: 40

Answers (3)

Aman Sharma
Aman Sharma

Reputation: 1

You could use $this->db->num_rows() or try below code

$check_username = $this->db->where('name', $name)->where('id !=', $user_id)->get('users')->num_rows();

if($check_username > 0) {
    $username = strtolower(str_replace(" ", ".", $name)) . $user_id;
} else {
    $username = strtolower(str_replace(" ", ".", $name));
}

$this->db->where('id', $user_id);
$this->db->update('users', array("username" => $username));

Upvotes: 0

chad
chad

Reputation: 838

You can use $this->db->count_all_results()

$check_username = $this->db->where('name', $name);
    $check_username = $this->db->where('id !=', $user_id);
    $check_username = $this->db->get('users');

    if($this->db->count_all_results() >= 1) {
        $username = strtolower(str_replace(" ", ".", $name)) . $user_id;
    } else {
        $username = strtolower(str_replace(" ", ".", $name));
    }

    $this->db->where('id', $user_id);
    $this->db->update('users', array("username" => $username));

Upvotes: 0

Hikmat Sijapati
Hikmat Sijapati

Reputation: 7004

Use $this->db->num_rows() to check whether name is already present in database or not like belw:

$this->db->where('name', $name);
$this->db->where('id !=', $user_id);
$check_username = $this->db->get('users');

if($this->db->num_rows($check_username) >= 1) {
    $username = strtolower(str_replace(" ", ".", $name)) . $user_id;
} else {
    $username = strtolower(str_replace(" ", ".", $name));
}

$this->db->where('id', $user_id);
$this->db->update('users', array("username" => $username));

Upvotes: 2

Related Questions