How to check if email already exists in db with CodeIgniter

旧街凉风 提交于 2020-01-03 16:58:31

问题


I am doing application in CodeIgniter. I don't know how to compare email against db in CodeIgniter, please any one, help me.

Controller

public function signup()
{
    $this->load->view('signup');

}
public function savedata(){

$this->load->library('form_validation');        
$this->form_validation->set_rules('firstname', 'firstname', 'required'); 
$this->form_validation->set_rules('lastname', 'lastname', 'required'); 


if ($this->form_validation->run() == TRUE) // Only add new option if it is unique
{       
    $result = $this->account_model->insert();
    if($result > 0)
    {
    $data['message'] = "Added successfully";    

    $this->load->view('signup',$data);
    }
    else
    {
    $this->index(); 
    }
}
else
{
    $this->load->view('signup');
}
}

How to check whether email already exists or not?


回答1:


Add a rule:

$this->form_validation->set_rules('email', 'Email', 'callback_rolekey_exists');

In the same Controller:

function rolekey_exists($key) {
  $this->roles_model->mail_exists($key);
}

In Model,

function mail_exists($key)
{
    $this->db->where('email',$key);
    $query = $this->db->get('users');
    if ($query->num_rows() > 0){
        return true;
    }
    else{
        return false;
    }
}

Reference




回答2:


Suppose, you have user table and email column. So you have to add this line in form validation

$this->form_validation->set_rules('email','Email','required|valid_email|is_unique[users.email]');

Note And need an unique index in your email column

check Documentation




回答3:


Best Way

$this->form_validation->set_rules(
            'email', 'Email', 'valid_email|required|is_unique[usr_user.user_email]',
            array('is_unique' => 'This %s already exists.')
        );



回答4:


 //in controller    
public function usernameExist($username)
{
    $user = $this->Model-> usernameExist($username);

    if ($user) {
        $this->form_validation->set_message(
            'usernameExist',
            'Username  is already exist.'
        );
        return false;
    } else {
        return true;
    }
}



回答5:


function username_Exist($key)
{
    $this->db->where('username', $key);
    $query = $this->db->get('signup');
    if ($query->num_rows() > 0) {
        return true;
    } else {
        return false;
    }
}

//type this in model




回答6:


 $this->form_validation->set_rules('username', 'User', 'trim|required|callback_username_Exist');
        //type in controller in form validation


来源:https://stackoverflow.com/questions/27294776/how-to-check-if-email-already-exists-in-db-with-codeigniter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!