the username is correct but the password is wrong and it doesn’t redirect

Тhe actual reason for this unexpected behaviour is that you are calling sqlsrv_fetch_array() twice, so while ($row = sqlsrv_fetch_array($stmt)) { ... } simply doesn’t return any rows.

But you need to consider at least the following:

  • Always use parameters in your statements to prevent possible SQL injection issues. As is mentioned in the documentation … sqlsrv_query function does both statement preparation and statement execution, and can be used to execute parameterized queries.
  • Do not store passwords in plaintext in a database.

The following basic example, based on your code, is a possible solution to your problem:

<?php
session_start();
if (!empty($_POST)) {

    if (isset($_POST['username']) && isset($_POST['password'])) {

        $username = $_POST['username']; 
        $password = $_POST['password'];
        
        $connectionInfo = array("Database"=>"WebUIUsers", "UID"=>"DBUser", "PWD"=>"Password1234");
        $conn = sqlsrv_connect("sqlserver01", $connectionInfo);
        if ($conn === false) {
            //echo "Connection to database could not be established: ".print_r(sqlsrv_errors(), true);
            header("Location: ./index.php");
            exit;
        }   

        $sql = "SELECT * FROM tbl_webui_users WHERE username = ?";
        $prms = array($username);
        $stmt = sqlsrv_query($conn, $sql, $prms);
        if ($stmt === false) {
            //echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
            header("Location: ./index.php");
            exit;
        }   
        
        // User doesn't exists
        if (!sqlsrv_has_rows($stmt)) {
            header("Location: ./index.php");
            exit;
        }   
        
        // User exists, but the password is wrong
        $row = sqlsrv_fetch_array($stmt));
        if ($row === false) {
            header("Location: ./index.php");
            exit;
        }   
        if ($row["password"] === $password) {
            $_SESSION['user_session'] = $username;
            header("Location: ./dashboard.php");
        } else {
            header("Location: ./index.php");
        }
    }

}

?>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top