在php

时间:2018-04-22 13:14:53

标签: php mysql

每当我输入错误的用户名时,结果页面会给出第二个else输出。如果用户输入错误的用户名,我希望第一个其他显示在屏幕上,而当有人试图直接从网址进入登录页面而不输入任何名称时,显示第二个。是的session_start();已在两个页面上声明。

<?php

if (isset($_POST["submit"]))
    {
    $username = $_POST["username"];
    $conn = new mysqli("localhost", "root", "", "test");
    $result = $conn->query("select name from students where name = '$username'");
    if ($result->num_rows > 0)
        {
        $_SESSION["username"] = $username;
        echo "You are logged in. This is the welcome page. Welcome user: " . $username;
        }
      else
        {
        echo "Invalid username. Try again.";
        }

    $conn->close();
    }
  else
    {
    echo "Come through proper ways.";
    }

?>

2 个答案:

答案 0 :(得分:2)

可能出现的问题

通常,您省略了一些可能导致意外行为的错误管理,这会破坏您的条件逻辑。

  1. 您必须检查$_POST['username'],考虑可以在没有用户名的情况下接收$_POST['submit'](网络上充满惊喜)。区分丢失的用户名和错误的用户名的最佳方法是直接使用isset()empty()进行检查。

  2. 您必须检查数据库连接是否成功,以避免conn->connect_errno出现异常。

  3. 您必须检查$result是否评估为false,这意味着存在查询错误。

  4. 您可以在将$username插入请求之前将其<?php if ( isset($_POST['submit']) && isset($_POST['username']) && !empty($_POST['username']) ) { $conn = new mysqli("localhost", "root", "", "test"); $username = mysqli_real_escape_string($conn, $_POST["username"]); // check connection if ( $conn->connect_errno ){ die("Data access denied ([".$conn->connect_errno."] ".$conn->connect_error.")"); } $result = $conn->query("select name from students where name = '$username'"); // check for query errors if (!$result) { die("Data access denied (invalid query)"); } // ... } else { echo "Come through proper ways."; } 转义,我不知道 mysqli 如何管理SQL注入。

  5. 可能的解决方案

    The script flake8.exe is installed in 'c:\users\me\appdata\local\programs\python\python36-32\Scripts' which is not on PATH.
    Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
    

答案 1 :(得分:0)

尝试使用以下代码

<?php
if(isset($_POST["submit"] && array_filter($_POST) && $_POST['username']){
    $conn = new mysqli("localhost", "root", "", "test") or die('Database Connection Failure ' . (($conn->connect_errno) ? $conn->connect_error : ''));
    $username = mysqli_real_escape_string($conn, $_POST['username']);
    $result = $conn->query("select name from students where name = '{$username}'");
    if($result->num_rows > 0){
        // success
        $_SESSION["username"] = $username;
        echo "You are logged in. This is the welcome page. Welcome user: " . $username;
    }else{
        echo "Invalid username. Try again.";
    }
    $conn->close();
}else{
    echo "Come through proper ways.";
}