如果条件不正常,则检查不正确

时间:2017-03-30 06:30:55

标签: php codeigniter

如果名称已经存在,我已经创建了一个在名称的贝司上创建自动用户名的函数,那么用户名将根据用户ID进行创建,但是当我创建用户并测试该名称是否已经存在于数据库中时它正在创建用户名和用户ID,因为它不应该是因为测试名称不在数据库中。这是我的代码

// $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));

3 个答案:

答案 0 :(得分:2)

使用$this->db->num_rows()检查数据库中是否已存在名称,或者不是,如下所示:

$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));

答案 1 :(得分:0)

您可以使用$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));

答案 2 :(得分:0)

您可以使用$this->db->num_rows()或尝试以下代码

$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));