我正在尝试创建一个表单验证回调函数,但我遇到了一些麻烦。
我要做的是创建一个联系表单,其中加入邮件列表选项。如果选中加入邮件列表的选项,我希望将该人员的姓名和电子邮件添加到邮件列表数据库中。这部分工作正常,但我也想要检查数据库的功能,以确保添加的电子邮件地址是唯一的,这是我无法理解的。
控制器:
public function contact()
{
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'your name', 'required', array('required'=>"<p class='required'>Please provide %s</p><br>"));
$this->form_validation->set_rules('email', 'your email address', 'required', array('required'=>"<p class='required'>Please provide %s</p><br>"));
if($this->form_validation->run() == FALSE)
{
$this->load->view('templates/headder');
$this->load->view('contact');
$this->load->view('templates/footer');
}
else
{
$this->load->library('email');
$name = $this->input->post('name');
$email = $this->input->post('email');
$phone = $this->input->post('phone');
$message = $this->input->post('message');
$list = $this->input->post('mailing_list');
$email_message = "Name: $name<br>Email: $email<br>Phone: $phone<br>Message:<br>$message";
$this->email->initialize();
$this->email->from($email, $name);
$this->email->to('myaddress@mydomain.co.uk');
$this->email->subject('New Query');
$this->email->message($email_message);
$this->email->send();
if($this->email->send()){
$this->load->view('send_error');
}
else
{
if($list == 'no')
{
$this->load->view('sent');
}
else
{
$this->form_validation->set_rules('email', 'Email', 'is_unique[mail_list, email]');
if($this->form_validation->run() == FALSE)
{
$this->load->model('mailing_listm');
$this->mailing_listm->add_name();
$this->load->view('sent');
}
else
{
$this->load->view('contact');
}
}
}
}
}
错误讯息:
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' email 'myaddress@mydomain.co.uk' LIMIT 1' at line 3
SELECT * FROM `mail_list`, `email` WHERE mail_list, email 'myaddress@mydomain.co.uk' LIMIT 1
Filename: libraries/Form_validation.php
Line Number: 1134
希望有人能够让我知道这次我做了多少蠢事。
此外,这个功能变成了一个怪物,它是我每次尝试写的最复杂的东西。有什么方法可以将它拆分出来,以便它由几个较小的功能组成,而不是一个庞大的功能?
谢谢,
EDIT 我已经根据下面关于使用is_unique的评论更新了我的代码,但是现在我收到了一条错误消息。
EDIT 型号:
Public function add_name()
{
$this->name = $this->input->post('name');
$this->email = $this->input->post('email');
$this->db->insert('mail_list', $this);
}
答案 0 :(得分:5)
用于检查唯一字段,在codeigniter中有一个验证规则。
is_unique[table.field]