php 如何使用 CodeIgniter 检查数据库中是否已存在电子邮件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27294776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if email already exists in db with CodeIgniter
提问by Vijaykarthik
I am doing application in CodeIgniter. I don't know how to compare email against db in CodeIgniter, please any one, help me.
我正在 CodeIgniter 中进行应用。我不知道如何在 CodeIgniter 中将电子邮件与数据库进行比较,请任何人帮助我。
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?
如何检查电子邮件是否已经存在?
回答by Imran
Suppose, you have usertable and emailcolumn. So you have to add this line in form validation
假设你有user表和email列。所以你必须在表单验证中添加这一行
$this->form_validation->set_rules('email','Email','required|valid_email|is_unique[users.email]');
NoteAnd need an unique index in your emailcolumn
注意并且在您的email列中需要一个唯一索引
check Documentation
检查文档
回答by Pupil
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;
}
}
回答by Samithe Adhikari
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.')
);
回答by Samuel Ofosu Atuahene
//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;
}
}
回答by Samuel Ofosu Atuahene
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
//在模型中输入
回答by Samuel Ofosu Atuahene
$this->form_validation->set_rules('username', 'User', 'trim|required|callback_username_Exist');
//type in controller in form validation

