0

I created a login wherein the user must input a username and password. the username and password will be validated. if the username and password did match in the records from the database then it should continue but what happened is that if the username and password did not match from the data in the database it still continue. would be there any better codes for this? i'm using PHP with MS SQL SERVER.

<?php
session_start();
$serverName = "MELODY-PC\SQLEXPRESS";
$connectionInfo = array( "Database"=>"customerdb", "UID"=>"dbadmin", "PWD"=>"melodyjerah" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}
$username = $_REQUEST['user'];
$password  = $_REQUEST['pass'];
$tsql = "SELECT * FROM accounting_login WHERE username='$username' AND password='$password'";
$stmt = sqlsrv_query( $conn, $tsql, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
if($stmt == true){
    $_SESSION['valid_user'] = true;
    $_SESSION['username'] = $username;
    header('Location: accounting_page.php');
    die();
}else{
    header('Location: error.html');
    die();
}
?>
<html>
<head><title></title>
    <link rel="stylesheet" type="text/css" href="login.css">
</head>
<body>
<div id="loginform">
<center>
<form action="connectdb.php" method="POST">
    <table border=0>
        <tr><th colspan=2><h2>ACCOUNTING LOGIN</h2></th></tr>
        <tr><td colspan=2><center>Login Type: <select onchange="location = this.options[this.selectedIndex].value;">
            <option value="login.php">Accounting</option>
            <option value="login_manager.php">Manager</option>
            <option value="login_seller.php">Seller</option>
        </select></center></td></tr>
        <tr><td colspan=2>&nbsp</td></tr>
        <tr><td>Username:</td><td><input type="text" name="user"></td></tr>
        <tr><td>Password:</td><td><input type="password" name="pass"></td></tr>
    </table>
    <br>
    <input type="submit" value="LOGIN" class="submit">
    <input type="button" value="CANCEL" class="submit" onclick="window.location.href='newformat.html'">
</form>
</center>
</form>
</body>
</html>
Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78
kwekwe
  • 47
  • 1
  • 6
  • The statement will always return true as long as the query is valid, even with no returned rows. You should use the [count of returned values](http://php.net/manual/de/function.sqlsrv-num-rows.php), and you shouldn't store the passwords as clear text in the database in the first place. – Gerald Schneider Apr 18 '16 at 13:29
  • Also note that your code is open for SQL injections. – Gerald Schneider Apr 18 '16 at 13:33

0 Answers0