6

I am using Active Record on CodeIgniter. I am confused on which approach I should take. Currently, our login system let's the user to use username/email for the login along with the password. But my current active record, seems to let the user logged in if he choose to use the email + no password.

Right now this is my query:

$this->db->select('id,level,email,username');
$this->db->where('email',$user);
$this->db->or_where('username',$user);
$this->db->where('password',$pass);
$query = $this->db->get('users');

if($query->num_rows>0)
  return TRUE;
else
  return FALSE;

Sample inputs:

  • Username: test | Password: pass | Result: Success
  • Username: test | Password: empty | Result: Failed
  • Username: test@domain.com | Password: pass | Result: Success
  • Username: test@domain.com | Password: empty | Result: Success

The fourth test input must be Failed in result, but it seems that it logs the user even if the password is empty.

Leandro Garcia
  • 3,138
  • 11
  • 32
  • 44

3 Answers3

18

The issue is probably that you need to add brackets when mixing AND’s and OR’s in a WHERE clause. Try this:

$this->db->select('id,level,email,username');
$this->db->where("(email = '$user' OR username = '$user') 
                   AND password = '$pass'");
$query = $this->db->get('users');
safarov
  • 7,793
  • 2
  • 36
  • 52
4

@RidIculous is right. This is a correct way to do it:

$user = $this->db->escape($user);
$this->db->select('id,level,email,username');
$this->db->where("(email = $user OR username = $user)");
$this->db->where('password', $pass);
$query = $this->db->get('users');

Or a format I prefer (PHP 5+)

$user = $this->db->escape($user);
$query = $this->db
    ->select('id,level,email,username')
    ->where("(email = $user OR username = $user)")
    ->where('password', $pass)
    ->get('users');
Tum
  • 6,937
  • 2
  • 25
  • 23
0
$conditions = '(`username`="'.$username.'" OR `email`="'.$email.' OR `mobile`="'.$mobile.'"') AND `password`="'.$password.'"';          
$query = $this->db->get_where('table_name', $conditions);
$result = $query->result();
Amin
  • 681
  • 4
  • 9
  • 27
  • 1
    While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. **Flaggers / reviewers:** [For code-only answers such as this one, downvote, don't delete!](//meta.stackoverflow.com/a/260413/2747593) – Scott Weldon Dec 01 '16 at 00:23