1

I created a login form in PHP and now I have a password, email and username stored in the database when I use this query in my database form works correctly

$query = "SELECT * FROM users WHERE email = '$email'  AND password='$password' ";

But when I add username functionality too it does not work correctly this is my username code

$query = "SELECT * FROM users WHERE username='$email' or email = '$email'  AND password='$password' ";

Basically what happens is this, when I add username functionality when I try to login with username and type any password it logs in but when I try with email and try any password it says invalid and it works only with correct password now I want it to work correctly with username too

this is my whole code

<?php
 session_start();
 if (!isset($_SESSION['is_login'])) {

   # code...

if (isset($_POST['btn_login'])) {
  $email = mysqli_real_escape_string($con,trim($_POST['email'])); 
  $password = mysqli_real_escape_string($con,md5(trim($_POST['password'])));

 $query = "SELECT * FROM users WHERE username='$email' or email = '$email'  AND password='$password' ";

 $fire = mysqli_query($con,$query);
 if ($fire) {
if (mysqli_num_rows($fire) == 1) {


  $_SESSION['is_login'] = 'true';
  $_SESSION['email'] = $email;

  header("Location: dashboard");

}else{
  $errorfname= '<p style="color:#cc0000;">invalid username or password</p>';
}
}
}
}else{
  header("Location: dashboard.php");
}
?>
3
  • Does you username also contain email values Commented Oct 7, 2018 at 6:34
  • yes both email and username have same input field @MadhurBhaiya Commented Oct 7, 2018 at 6:35
  • 2
    This might be an issue of operator precedence. Try WHERE (username='$email' or email = '$email') AND password... Commented Oct 7, 2018 at 6:35

2 Answers 2

1

Need to use parentheses properly. Put parentheses ( .. ) around OR condition checking.

 $query = "SELECT * FROM users WHERE (username='$email' or email = '$email')  
                                      AND password='$password' ";

From MySQL Documentation:

AND, &&
XOR
OR, ||

AND takes higher precedence than OR. So, basically without using parentheses, email = '$email' AND password='$password' would have executed first. Now this may return false if password is incorrect. But then, username='$email' will be executed, and it will return true if correct email id is used. Now, true or false = true. So even with wrong password, but correct email id, anybody could have logged in.

Sign up to request clarification or add additional context in comments.

Comments

0

Your query should be

$query = "SELECT * FROM users WHERE (username='$email' or email = '$email')  AND password='$password' ";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.