2014-07-17 44 views
0

我在網上查找,發現了很多與我的密切相關的問題,但沒有什麼能夠幫助解決我的問題。它很簡單,即時通訊試圖遍歷我的電子郵件表來檢查電子郵件是否存在,如果不存在,請繼續並添加它。事情是,它總是添加電子郵件,查詢不會返回任何東西(甚至它應該)。也即時使用codeigniter,它有助於或複雜的情況。檢查codeigniter中的電子郵件

這裏是方法:

public function add_email(){ 
     $email = $this->input->post('email'); 
     $query = $this->db->query("SELECT * FROM emails WHERE email LIKE '$email'"); 
     $query->result(); 
     if($query->num_rows() == 0){ 
      $data = array(
       'email' => $this->input->post('email'), 
       'name' => $this->input->post('name') 
      ); 
      return $this->db->insert('emails', $data); 
     } 
     return FALSE; 
    } 

感謝提前

+0

如果您檢查是否存在確切的電子郵件地址,爲什麼您使用'LIKE'而不是'='? –

+0

@PatrickQ爲什麼不呢? 'LIKE'使得查詢不區分大小寫。除非使用通配符('%')運算符,否則不會執行任何通配符匹配。由於發送給Bob @ domain.com的電子郵件與bob @ domain.com相同,這是有道理的(忽略了明顯的SQL注入漏洞)。 – sjagr

+0

@sjagr只要看看OP是否有充分的理由,也許不會濫用它。並不意味着它本身就是錯誤的。另外,儘管大多數電子郵件服務確實會將不同情況的電子郵件地址等同起來,但技術上而言,「bOB @ example.com」與「Bob @ example.com」不同。 –

回答

0

我做同樣的事情在我的項目,以用戶登錄模塊。下面的代碼

用途: -

function email_check($srt) { 
    $query = $this->db->get_where('emails', array('email_id' => $srt), 1); 
    if ($query->num_rows() == 1) { 
     return true; 
    } else { 
     return false; 
    } 
} 

function add_email() { 
    $email = filter_input(INPUT_GET, email, FILTER_SANITIZE_SPECIAL_CHARS); 
    $name = filter_input(INPUT_GET, name, FILTER_SANITIZE_SPECIAL_CHARS); 

    if ($this->email_check($email)) { 
     $data = array(
      'email' => $this->input->post('email'), 
      'name' => $this->input->post('name') 
     ); 
     return $this->db->insert('emails', $data); 
    } else { 
     echo 'email already exit'; 
    } 
} 
0

,說明你將它們插入到數據庫之前小寫您的郵件(and you validate your post data),你可以做以下

在你控制器

$data = array(
    'email' => strtolower($this->input->post('email')), 
    'name' => $this->input->post('name') 
); 

$this->model_name->add_email($data); 

在您的模型

public function add_email($data) { 

    $this->db->where('email', $data['email']); 
    $this->db->from('emails'); 

    if($this->db->count_all_results() == 0) { 

     return $this->db->insert('emails', $data); 
    } else { 

     return FALSE; 
    } 
}