PHP表单需要提交两次以设置会话

So I am trying to implement a login on my website but for some reason the form needs to have submit pressed twice to effectively login. I am at a complete loss as to why

<?php
    session_start();
if(isset($_SESSION["username"])){
        print('<p>'.$_SESSION["username"]." is currently logged in");
        print('<form action="logout.php"><input type="submit" value="Log out"></form>');
    }
else{
print('<form action="index.php" method="post">
        Username: <input type="text" name="username"/><br/>
        Password: <input type="password" name="password"/><br/>
        <input type="submit" value="Log In" name="submit"/>
    </form>');
include('config.php');

if(isset($_POST['submit'])) {
    $username = mysql_real_escape_string(htmlentities($_POST['username']));
    $password = hash('sha256', mysql_real_escape_string(htmlentities($_POST['password'])));
    $mysqli = new mysqli( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
    $qstring = 'SELECT * FROM login WHERE username = "'.$username.'" AND password = "'.$password.'"';
    $result = $mysqli->query($qstring);
    if($result->num_rows ==1)
    {

        $_SESSION['username']=$username;
        $_SESSION['password']=$password;       
    }

Since you have all your code for login, processing and showing the user is logged in at the same page with no redirect after the user is successful logged in, it takes you 2 submits to see the logged in page.

I would suggest you splitting your login page from what you currently have into a login.php and a home.php.

Also you should avoid querying for username and password, you should only need to retrieve the username and compare the password instead and also avoid saving the password on the session its extremely unneeded.

login.php would have:

<?php
session_start();
// Your database info
$db_host = '';
$db_user = '';
$db_pass = '';
$db_name = '';

if (isset($_SESSION['username']))
{
    // If the user is already logged in send to home
    header("Location: home.php");
}
else
{
    // if the user is not logged in but have submitted the login page, 
    // check its credentials and redirect to home page
    if (isset($_POST['submit']))
    {
        if (isset($_POST['username']) && isset($_POST['password']))
        {
            $con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
            if ($con->connect_error)
            {
                die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
            }

            $sql = "SELECT username, password FROM login WHERE username = ?";
            if (!$result = $con->prepare($sql))
            {
                die('Query failed: (' . $con->errno . ') ' . $con->error);
            }

            if (!$result->bind_param('s', $_POST['username']))
            {
                die('Binding parameters failed: (' . $result->errno . ') ' . $result->error);
            }

            if (!$result->execute())
            {
                die('Execute failed: (' . $result->errno . ') ' . $result->error);
            }

            $result->store_result();
            if ($result->num_rows == 0)
            {
                die('No username found...');
            }

            $password = hash('sha256', $_POST['password']);
            $result->bind_result($db_username, $db_password);
            $result->fetch();

            if ($password == $db_password)
            {
                $_SESSION['username'] = $db_username;
                header("Location: home.php");
                exit;
            }
            else
            {
                $error = "Username or password does not match...";
            }
        }
        else
        {
            $error = "Fill the username and password to login...";
        }
    }
}
// Show the form and/or possible error messages to user if applicable
?>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<?php if (isset($error)) echo $error, '<br>'; ?>
<form method="POST" action="index.php">
<label>Username</label><br /><input type="text" name="username" value=""><br />
<label>Password</label><br /><input type="password" name="password" value=""><br />
<input type="submit" name="submit" value="Login">
</form>
</body>
</html>

And at home.php:

<?php
session_start();
if (!isset($_SESSION['username']))
{
    // send user back to login page if he is not logged in
    header("Location: login.php");
    exit;
}
// show the home page
?>
<p><? echo $_SESSION["username"]; ?> is currently logged in.
<form action="logout.php">
<input type="submit" value="Log out">
</form>

First you need to set session_start(). Then your problem is because after getting logged in first time and setting session you don't redirect your page. So first time when page lands session is empty and you get logged in and set session but no redirect. When you again submit it is already set, so it shows you logged in. So change your code to

   if($result->num_rows ==1)
   {
     $_SESSION['username']=$username;
     $_SESSION['password']=$password;    
     header('Location: index.php');
   }

Your basic authentication logic is wrong.

Your current cycle is this:

First load:
    Not logged in -> show form
    Submit
Second load:
    Process form
    Set session
Third load:
    Validate session

If what you posted is your full and actual production code, then you have a few missing closing braces, and I'm unsure where you wish to have include('config.php'); inside or outside of your first conditional statement.

Plus, you're mixing your SQL functions. mysql_* and mysqli_* do not mix.

This:

$username = mysql_real_escape_string(htmlentities($_POST['username']));
$password = hash('sha256', mysql_real_escape_string(htmlentities($_POST['password'])));

should be changed to:

$username = mysqli_real_escape_string($mysqli,$_POST['username']);
$password = hash('sha256', mysqli_real_escape_string($mysqli,$_POST['password']));

and placed below your DB connection.

This is questionable but feel I need to mention it. If you indeed have a function called start_session(); ok. If not then that may need to be changed to session_start();

<?php
session_start();
//  start_session();
if(isset($_SESSION["username"])){
        print('<p>'.$_SESSION["username"]." is currently logged in");
        print('<form action="logout.php"><input type="submit" value="Log out"></form>');
    }
else{
print('<form action="index.php" method="post">
        Username: <input type="text" name="username"/><br/>
        Password: <input type="password" name="password"/><br/>
        <input type="submit" value="Log In" name="submit"/>
    </form>');
include('config.php');

} // first missing brace and unsure if you want
// your included file inside of it, or out.

if(isset($_POST['submit'])) {

    $mysqli = new mysqli( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
    $username = mysqli_real_escape_string($mysqli,$_POST['username']);
    $password = hash('sha256', mysqli_real_escape_string($mysqli,$_POST['password']));
    $qstring = 'SELECT * FROM login WHERE username = "'.$username.'" AND password = "'.$password.'"';
    $result = $mysqli->query($qstring);
    if($result->num_rows ==1)
    {
        $_SESSION['username']=$username;
        $_SESSION['password']=$password;
    }

} // second missing brace