使用codeigniter登录用户名或电子邮件

时间:2014-05-15 14:57:27

标签: php mysql codeigniter login

嗨,我在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;
    }
  }
}

有人可以帮我解决这个问题吗?非常感谢。

1 个答案:

答案 0 :(得分:2)

您需要稍微更改模型,并在括号中添加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);