簡體   English   中英

如何使用CodeIgniter檢查db中是否已存在電子郵件

[英]How to check if email already exists in db with CodeIgniter

我在CodeIgniter中做應用程序。 我不知道如何在CodeIgniter中比較電子郵件與db,請任何人,幫助我。

調節器

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');
}
}

如何檢查電子郵件是否已存在?

假設您有user表和email列。 所以你必須在表單驗證中添加這一行

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

注意並且需要在email列中添加唯一索引

檢查文檔

添加規則:

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

在同一個控制器中:

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

在模型中,

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

參考

最好的辦法

$this->form_validation->set_rules(
            'email', 'Email', 'valid_email|required|is_unique[usr_user.user_email]',
            array('is_unique' => 'This %s already exists.')
        );
 //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;
    }
}
function username_Exist($key)
{
    $this->db->where('username', $key);
    $query = $this->db->get('signup');
    if ($query->num_rows() > 0) {
        return true;
    } else {
        return false;
    }
}

//在模型中輸入

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM