codeigniter active record where, or_where?

Leandro Garcia picture Leandro Garcia · Mar 26, 2012 · Viewed 24.9k times · Source

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: [email protected] | Password: pass | Result: Success
  • Username: [email protected] | 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.

Answer

safarov picture safarov · Mar 26, 2012

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');