2

Good day everyone:

I'm having trouble making a login page for my PHP application with a connection to an MS SQL Server database.

I can connect to the database using this code:

<?php
$serverName = "DESKTOP-FDJAOMJ\\sqlexpress"; //serverName\instanceName
$connectionInfo = array( "Database"=>"sgo", "UID"=>"arm", "PWD"=>"arm123");
$con = sqlsrv_connect( $serverName, $connectionInfo);

if( $con ) {
     echo "Connection established.<br />";
}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}
?>

And then the connection is ok. But, I've only ever worked with a MySQL backend, and this project requires MS SQL, and I can't get the MS SQL login page to work. My code is below:

<!DOCTYPE html>
<html>
    <body>
        <?php
        require('db.php');
        session_start();
        // If form submitted, insert values into the database.
        if (isset($_POST['username'])){
                // removes backslashes
            $username = stripslashes($_REQUEST['username']);
                //escapes special characters in a string
            //$username = unpack($con,$username);
            $password = stripslashes($_REQUEST['password']);
            //$password = addslashes($con,$password);
            //Checking is user existing in the database or not
            $query = "SELECT * FROM `users` WHERE username='$username' and password='$password'";
            $params = array();
            $result = sqlsrv_query($con,$query,$params) or die(sqlsrv_errors());
            $rows = sqlsrv_num_rows($result);
                if($rows==1){
                $_SESSION['username'] = $username;
                    // Redirect user to index.php
                header("Location: index.php");
                 }else{
            echo "<div class='form'>
        <h3>Username/password is incorrect.</h3>
        <br/>Click here to <a href='login.php'>Login</a></div>";
            }
            }else{
        ?>
        <div class="form">
            <h1>Log In</h1>
            <form action="" method="post" name="login">
                <input type="text" name="username" placeholder="Username" required />
                <input type="password" name="password" placeholder="Password" required />
                <input name="submit" type="submit" value="Login" />
            </form>
            <p>Not registered yet? <a href='registration.php'>Register Here</a></p>
        </div>
        <?php } ?>
    </body>
</html>

When I type in the username and password I get an error:

Notice: Array to string conversion in C:\wamp\www\PHPwebpage\login.php on line 18. line 18 is ""$result = sqlsrv_query($con,$query,$params) or die(sqlsrv_errors());"".

users table variables: id int username varchar(50) email varchar(100) password varchar(50) trn_date datetime

3 Answers 3

4

Although I'm not a SQL Server coder, there are a few things you will need to change...

    $query = "SELECT * FROM [users] WHERE username='$username' and password='$password'";
    $params = array();
    $result = sqlsrv_query($con,$query,$params) or die( print_r( sqlsrv_errors(), true));

With MySQL, you can use backticks round table names and column names, but not in SQL Server - as pointed out by Parfait in the comments, you should use [] instead for reserved words.

With the error your getting - sqlsrv_errors() returns an array, so I've changed the die() to put out print_r( sqlsrv_errors(), true).

I would also recommend looking into prepared statements to avoid SQL injection and password_hash() to improve the password processing.

Sign up to request clarification or add additional context in comments.

4 Comments

This helped. For whatever reason, now I'm getting a line that reads: Connection established. Array ( [0] => Array ( [0] => 42S22 [SQLSTATE] => 42S22 [1] => 207 [code] => 207 [2] => [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid column name 'username'. [message] => [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid column name 'username'. ) ) The query works in MS SQL Management Studio, but, not in PHP
Can you check the connection that you are connected to the right database. If you are then can you show the table definition in your question.
I added some information of the users table. I am connected to the correct database. With some further work the code seems to be working, except, I keep getting a message saying that my username and password are incorrect. I've printed the username and password variables in the code, and, they match what I am looking for in the query so they should work.
I know it's extra work, but you should look into password_hash(), one reference is on the answer the other is stackoverflow.com/questions/26536293/…. This will include making sure the column is long enough.
1

Currently, you are passing an empty array, $params into sqlserv_query() and not using qmark, ?, placeholders in your prepared statement to bind parameter values.

Consider fixing your parameterization setup and using try/catch and not raise actual errors on web page to users. Below raises the error in log files.

$username = stripslashes($_REQUEST['username']);
$password = stripslashes($_REQUEST['password']);

//Checking is user existing in the database or not
$query = "SELECT * FROM [users] WHERE username = ? and password = ?";
$params = array($username, $password);

try {
   $result = sqlsrv_query($con, $query, $params);
} catch(Exception $e) {
   error_log("$e");
}

2 Comments

This worked. The login page still has some issues, but, this solved my original question. Thanks
Great! Glad to help.
1
  1. Check the table have column name username by ALT+F1 at SSMS
  2. Your connected to right database or not (May be some where else it was overriden)
  3. use schema name before the table name as below

    $query = "SELECT * FROM dbo.[users] WHERE username='$username' and password='$password'";
    

3 Comments

That worked. But, now I'm getting the username and password are incorrect. I've printed the values of $username and $password, they match my inputs in the login boxes. Not sure why it's saying they are wrong.
$query = "SELECT * FROM dbo.[users] WHERE username='".$username."' and password='."$password." ' "; use the concate operate may be there are not replacing the actual query
use the concatenation operator after and before $username may be there are not replacing the actual query. $query = "SELECT * FROM dbo.[users] WHERE username='".$username."' and password='".$password."' ";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.