Login with either username or email using codeigniter
authentication, codeigniter, mysql, php
Solution
you'll need to change your model slightly and add `OR` clause in brackets:
$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);
Problem
Hi, I have this login script in codeigniter and it runs well. It uses the username to login. But I want that you can login with an email address also. So when user performs the login, he/she can choose either username or email to login. How will I be able to do that? Any help is appreciated. Here's my Login controller: ``` <?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'); } } ``` My model: ``` <?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; } } } ``` Can someone help me to figure this out? Thanks a lot.