Select query returning false on sql server in PHP


#1

I am using SQL(MSSQL) Server database on Windows Server. My database connection is working perfect. I am trying to get data using Select Query. Here is my code,

db_functions.php

 public function login($username, $password)
 {

   $sqlString = "SELECT CompId , BUCode , Role from 
   PRIME_APPUSR WHERE UserName = ? AND PassWord = ?";

   $params = array($username, $password);

    $stmt = sqlsrv_query($this->conn, $sqlString, $params);
    if ($stmt === false) {

        die(print_r(sqlsrv_errors(), true));
    }

    $rows = sqlsrv_has_rows($stmt);

    if ($rows === true) {

        while ($row = sqlsrv_fetch($stmt)) {

            $response["CompId"] = sqlsrv_get_field($stmt, 0);
            $response["BUCode"] = sqlsrv_get_field($stmt, 1);
            $response["Role"]   = sqlsrv_get_field($stmt, 2)

        }

        return $response;

    } else {
        return false;
    }

}

login.php

 <?php

  require_once 'db_functions.php';
  $db = new db_functions();

  if (isset($_POST['USERNAME']) && isset($_POST['PASSWORD'])) {

  $USERNAME = $_POST['USERNAME'];
  $PASSWORD = $_POST['PASSWORD'];

  $result1 = $db->login($USERNAME, $PASSWORD);

  if (!$result1) {

    $arr["response"] = "Error.";

  } else {

    $arr["response"] = $result1;

  }

  echo json_encode($arr);

  } else {

    $arr["response"] = "Invalid Parameters";
    echo json_encode($arr);

  }

?>

my question is , i am getting a false in return from this function. can anyone guide to solve this.?


#2

Why are you testing if $rows is true? It shouldn’t be, it should be data.

if($rows) // tests if there is an array or is false on failure.


#3

Your query is probably not matching any data. Is the PassWord column holding a plain-text password (it shouldn’t be) or a hash of the password (it should be)?

Next, you have far too much code. After you execute the query, all you need to do is try to fetch the single row of data and return the result. Replace everything starting with the $rows = … line to the end of the function/method with this -

    $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
    return $row; // this will either be the fetched associative array of data or a null if the query didn't match a row
} // this is the closing } for the function//method

If the stored password is a hash, using php’s password_hash() function, which it should be, you will need to add the password field to the SELECT term, eliminate the password field from the WHERE term, and add php logic, using password_verify(), to test if the submitted password matches the stored hashed password.