简体   繁体   中英

Username and Password Don't Match Output

I am in the process of creating a signup system using mysql and PHP. I have been able to connect the system to a database and it works for when the username and password entered are correct. However, when the username and password is not correct (ie anytime when the username/password pair is not stored in the database), it just leads to a blank white page. Currently, my code has it so that when the username and password are not correct, it prints our "Invalid username of password". Please see the code below, any help is appreciated. Thank you in advance!

    <?php

require_once 'source/session.php';
require_once 'source/db_connect.php';

if(isset($_POST['login-btn'])) {

    $user = $_POST['user-name'];
    $password = $_POST['user-pass'];

    try {
      $SQLQuery = "SELECT * FROM users WHERE username = :username";
      $statement = $conn->prepare($SQLQuery);
      $statement->execute(array(':username' => $user));

      while($row = $statement->fetch()) {
        $id = $row['id'];
        $hashed_password = $row['password'];
        $username = $row['username'];

        if(password_verify($password, $hashed_password)) {
          $_SESSION['id'] = $id;
          $_SESSION['username'] = $username;
          header('location: dashboard.php');
        }
        else {
          echo "Error: Invalid username or password";
        }
      }
    }
    catch (PDOException $e) {
      echo "Error: " . $e->getMessage();
    }

}

?>

 

Well, currently your SQL query would return a set with 0 rows for a non-existent user, but that would not cause an error. It would just be an empty result set. Therefore it would not go through the while loop, it would just terminate without an error.

Your logic is leaving out the check to see whether $statement->rowCount() is zero.

To clarify in case this answer is confusing: You have 0 results if you enter a username that doesn't exist... then you do while(0) so you never get into that part of the code. No password check is done. And no error is thrown, so you never escape the try{} and get into the catch{} portion of the code. There is nothing returned here if the username turns up zero results from the database. You need to add another error in that case.

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