Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if email already exists in db with CodeIgniter

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?

like image 778
Vijaykarthik Avatar asked Dec 03 '22 18:12

Vijaykarthik


2 Answers

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

like image 112
Imran Avatar answered Dec 06 '22 09:12

Imran


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

like image 42
Pupil Avatar answered Dec 06 '22 10:12

Pupil