0

我正在尝试拉入用户表,如果电子邮件已经在数据库中,我不希望用户能够使用相同的电子邮件添加另一行。下面的代码是我到目前为止汇总的代码,但它似乎无法正常工作。有没有人注意到我做错了什么?

    $email = $this->input->post('email');
    $password = $this->input->post('password');
    $firstname = $this->input->post('firstname');
    $lastname = $this->input->post('lastname');
    $usersAddress = $this->input->post('usersAddress');
    $usersCity = $this->input->post('usersCity');
    $usersState = $this->input->post('usersState');
    $phoneNumber = $this->input->post('phoneNumber');

    $query1 = $this->db->get('users');
    foreach($query1->result() as $row) {    
        if ($row->email == $email) {
            echo 'Sorry but this email is already in use. Please go back and use a different email.';
        } else {
            $data = array('email' => $email,
                          'password' => $password,
                          'firstname' => $firstname,
                          'lastname' => $lastname,
                          'usersAddress' => $usersAddress,
                          'usersCity' => $usersCity,
                          'usersState' => $usersState,
                          'phoneNumber' => $phoneNumber);
            $this->db->insert('users', $data); 
            $this->session->set_userdata('id', $this->db->insert_id());
            $this->session->set_userdata('logged', 'true');
            $this->session->set_userdata('firstname', $firstname);
            $this->session->set_userdata('lastname', $lastname);
            $this->session->set_userdata('email', $email);
            mail($email,"KyPlays.org","You have successfully regstered at KyPlays.org");
            header("Location: ".base_url()."index.php/routers/startpage?requestedPageType=regPart2");
        }
    }
4

2 回答 2

4

不需要循环。只需检查电子邮件是否正在使用:

$query = $this->db->get_where('users', array('email' => $email));
if ($query->num_rows() > 0) {
  // Show error message as email already exists in the database
} else {
  // Insert new user
}
于 2012-12-20T01:01:33.100 回答
3

您还可以使用内置的 form_validation 并使用以下内容:

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

另见: http ://ellislab.com/codeigniter/user-guide/libraries/form_validation.html

于 2012-12-23T00:01:38.217 回答