将表单输入与数据库进行比较

时间:2017-01-31 07:03:51

标签: javascript php html

file.html

<div id="id00" class="login">
    <form class="modal-content animate" action="chat1.php" method="POST">
        <div class="cross">
            <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">&times;</span>
        </div>
        <div class="form">
            <label><b>Username</b></label>
            <input type="text" placeholder="Enter Username" name="username" required>
            <label><b>Password</b></label>     
            <input type="password" placeholder="Enter Password" name="password" required>
            <button type="submit">submit</button>
        </div>
    </form>
</div>

chat1.php

<?php
    ob_start();
    $username = "root";
    $password = "";
    $hostname = "localhost";
    $dbname = "login";
    $dbhandle = mysqli_connect($hostname, $username, $password, $dbname) or die("unable to connect to MySQL");
    if(isset($_POST["username"],$_POST["password"]))
    {
        $user = $_POST["username"];
        $pass = $_POST["password"];
        $result1 = mysqli_query("SELECT password FROM login WHERE username = '".$user."'");
        $result2 = mysqli_query("SELECT username FROM login WHERE password = '".$pass."'");
        if($user == $result2 && $pass == $result1)
        {
            $_SESSION["logged_in"] = true;
            $_SESSION["naam"] = $name;
        }
        else
        {
            echo "incorrect username/password";
        }
    }
?>

我需要使用datatbase检查用户名和密码并允许登录。在我的代码中,它总是给我错误的。谁能帮助我?

enter code here

2 个答案:

答案 0 :(得分:1)

请尝试此代码

 <?php
        session_start();
        $username = "root";
        $password = "";
        $hostname = "localhost";
        $dbname = "login";
        $dbhandle = mysqli_connect($hostname, $username, $password, $dbname) or die("unable to connect to MySQL");
        if(isset($_POST["username"],$_POST["password"]))
        {
            $user = $_POST["username"];
            $pass = $_POST["password"];
            $result1 = mysqli_query("SELECT username, password FROM login WHERE username = '".$user."' and password = '".$pass."'");
            if(mysqli_num_rows($result1))
            { 
                $result = mysqli_fetch_row($result1);
                $_SESSION["logged_in"] = true;
                $_SESSION["naam"] = $result['username'];
$redirect="yoursuccessurl.php";
            }
            else
            {
                $redirect="yourfailureurl.php";
            }
        }

header("location: ".$redirect);
    ?>

注意所有这些代码都对sql注入开放

答案 1 :(得分:0)

您永远不会从密码中选择用户名 原因是:许多用户可以拥有相同的密码,出于安全考虑,应对密码进行哈希处理和存储。

此行是一个错误的查询。

  $result2 = mysqli_query("SELECT username FROM login WHERE password = '".$pass."'");

你应该做的是

 $result1 = mysqli_query("SELECT password FROM login WHERE username = '".$user."'");
if($pass == $result1)
        {
            $_SESSION["logged_in"] = true;
            $_SESSION["naam"] = $name;
        }