2012-12-20 45 views
0

我想拉用戶表,並且如果電子郵件已經在數據庫中,我不希望用戶能夠添加另一行與電子郵件相同下面的代碼是我到目前爲止所做的,但似乎並不正確。有人注意到我做錯了嗎?Codeigniter不允許用戶添加重複的電子郵件到db

$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"); 
     } 
    } 
+2

沒有得到所有的用戶,檢查單個電子郵件地址是否在數據庫中。 – 2012-12-20 00:52:22

+0

那麼改變查詢或foreach循環? –

+1

兩者,無需循環,檢查電子郵件,然後根據結果 – 2012-12-20 00:56:35

回答

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 
} 
+0

謝謝你。是的,我剛剛完成了重寫它,就像你寫了它,現在它完美的工作。 –

相關問題