简体   繁体   中英

Login PHP keeps returning invalid username or password even if the fields are correct?

So basically, when I press login on my form, even if my username and password are correct in the input fields, I keep getting the invalid username or password error. I am unsure how to fix this, as everything looks correct in my code. How would I fix this so I can log in? Here is the code:

$servername = "localhost";
$username   = "root";
$password   = "root";
$dbname     = "users";

$mysqli = new mysqli($servername, $username, $password, $dbname);

if ($mysqli->connect_error)
{
    die("Connection failed: " . $mysqli->connect_error);
}
else
{
    if (isset($_POST["username"]) && isset($_POST["password"]))
    {
        $username = (string)$_POST["username"];
        $password = (string)$_POST["password"];
        $result = $mysqli->query("SELECT * FROM `users` WHERE `username`='$username'");
        while($row = $result->fetch_assoc())
        {
            if ($username == $row['$username'] && $password == $row['password'])
            {
                $regKey = $row['regKey'];
                $_SESSION["reg"] = $regKey;
                die("YOU DID IT");
            }
            else
            {
                $mysqli->close();
                die("Error, invalid username or password");
            }
        }
    }
}

Thank you for taking your time to help.

Instead of this:

if ($username == $row['$username'] && $password == $row['password'])

try this:

if ($username == $row['username'] && $password == $row['password'])

You were most probably trying to fetch an invalid column $row['$username'] from the database.

Yes, as HawasKaPujaari say you were trying to fetch an invalid column.

But also, I think you can have some problems with your session, you need to initialize, like this:

@session_start();

Just before this:

$_SESSION["reg"] = $regKey;

Good luck!

What is the need of if(condition inside while loop).? Check your condition in sql query only.

.
.
.
$username = $_POST["username"];
$password = $_POST["password"];
$result = mysqli->query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$CountResult=mysql_num_rows($result);
if($CountResult==1)
{
  while($row = $result->fetch_assoc())
  {
      $regKey = $row['regKey'];
      $_SESSION["reg"] = $regKey;
      die("YOU DID IT");
  }
}
else
{
   $mysqli->close();
   die("Error, invalid username or password");
}
.
.
.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM