The actual reason for this unexpected behaviour is that you are checking the result from the sqlsrv_query() call, not the data returned from the executed statement.
You also need to consider the following:
- You are using
user in your SELECT statement and in your WHERE clause. USER is a reserved T-SQL keyword which returns the database user name, so you need to use [user] instead.
- Use parameters in your statement to prevent possible SQL injection issues. As is mentioned in the documentation, the
sqlsrv_query() function is well-suited for one-time queries and should be the default choice to execute queries unless special circumstances apply. This function provides a streamlined method to execute a query with a minimum amount of code. The sqlsrv_query function does both statement preparation and statement execution, and can be used to execute parameterized queries.
- Use
sqlsrv_has_rows() to check if the result set has one or more rows.
- As an additional note, do not store passwords in plain text, use hashed passwords.
The next example (based on the code in the question) is a possible solution to your problem:
<?php require 'db_conn.php'?>
<?php
// Session
session_start();
// Connection
$conn = sqlsrv_connect($serverName, $connectionInfo);
if ($conn === false) {
die ('Failed to connect to Database');
}
// Statement
if (!isset($_POST['inputUsername'], $_POST['inputPassword']) ) {
die ('Please fill both the username and password field!');
}
$usersql = "SELECT [User], [Password] FROM Users WHERE [User] = ? AND [Password] = ?";
$userparams = array($_POST['inputUsername'], $_POST['inputPassword']);
$userstmt = sqlsrv_query($conn, $usersql, $userparams);
//
if ($userstmt === false) {
$_SESSION['loggedin'] = FALSE;
header('Location: login.php');
exit;
}
if (!sqlsrv_has_rows($userstmt)) {
$_SESSION['loggedin'] = FALSE;
header('Location: login.php');
exit;
}
//
$userrow = sqlsrv_fetch_array($userstmt, SQLSRV_FETCH_ASSOC);
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
sqlsrv_free_stmt($userstmt);
sqlsrv_close($conn);
header('Location: home.php');
?>