2014-05-15 174 views
1

嗨,我有codeigniter這個登錄腳本,它運行良好。它使用用戶名登錄。但我希望你也可以用電子郵件地址登錄。因此,當用戶執行登錄時,他/她可以選擇用戶名或電子郵件登錄。我將如何做到這一點?任何幫助表示讚賞。使用用戶名或電子郵件使用codeigniter登錄

這裏是我的登錄控制器

<?php if (! defined('BASEPATH')) exit('No direct script access allowed'); 
class Login extends CI_Controller { 


    public function __construct(){ 
    parent::__construct(); 
    $this->load->library('form_validation'); 
    $this->load->model('users_model','um'); 
    $this->load->library('session'); 

    if($this->session->userdata('loggedIn')){ 
     redirect('homepage'); 
    } 
    } 


    public function check_database($password){ 
    $username = $this->input->post('username'); 
    $result = $this->um->login($username, $password); 
    if($result){ 
     $sess_array = array(); 
     foreach($result as $row){ 
     $sess_array = array(
         'id'=>$row->id, 
         'username'=>$row->username 
        ); 
     $this->session->set_userdata('loggedIn',$sess_array); 
     } 
     return true; 
    }else{ 
     $this->form_validation->set_message('check_database', 'Invalid Username or Password.'); 
     return false; 
    } 
    } 

    public function verifyLogin(){ 
    $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean'); 
    $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database'); 
    if($this->form_validation->run() == FALSE){ 
     $this->data['title'] = 'Login'; 

     $this->load->view('templates/header',$this->data); 
     $this->load->view('pages/login'); 
     $this->load->view('templates/footer'); 
    }else{ 
    //redirect('homepage', 'refresh'); 
     redirect('homepage'); 
    } 

    } 

    public function index(){ 
    $this->data['title'] = 'Login '; 

    $this->load->view('templates/header', $this->data); 
    $this->load->view('pages/login'); 
    $this->load->view('templates/footer'); 
    } 
} 

模式

<?php if (! defined('BASEPATH')) exit('No direct script access allowed'); 

class Users_model extends CI_Model { 
    public function login($username, $password){ 
    $sha_password = sha1($password); 
    $this->db->select(' 
       users.id, 
       users.username, 
       users.email, 
       users.password') 
       ->from('users') 
       ->where('username', $username) 
       ->where('password', $sha_password); 
    $query = $this->db->get(); 
    if($query->num_rows() == 1){ 
     return $query->result(); 
    }else{ 
     return false; 
    } 
    } 
} 

有人可以幫我想出解決辦法?非常感謝。

回答

0

你需要稍微改變你的模型,並在括號內添加OR條款:

$this->db->select(' 
      users.id, 
      users.username, 
      users.email, 
      users.password') 
      ->from('users') 
      ->where("(users.email = '$username' OR users.username = '$username')") 
      ->where('password', $sha_password); 
+0

嘿感謝它現在的作品! – bobcatnyxz

相關問題