[英]How to check if email already exists in db with CodeIgniter
I am doing application in CodeIgniter. 我在CodeIgniter中做应用程序。 I don't know how to compare email against db in CodeIgniter, please any one, help me.
我不知道如何在CodeIgniter中比较电子邮件与db,请任何人,帮助我。
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? 如何检查电子邮件是否已存在?
Suppose, you have user
table and email
column. 假设您有
user
表和email
列。 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 注意并且需要在
email
列中添加唯一索引
check Documentation 检查文档
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;
}
}
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.')
);
//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;
}
}
//type this in model //在模型中输入
$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.