管理员登录php mysqli数据库

时间:2018-11-25 04:45:25

标签: php database forms post mysqli

我有一个简单的HTML表单,它发布到我的PHP页面,该页面完美地连接到我的MYSQL DB。我认为该连接可以很好地进行检查,但是让我的$ user和$ pass变量正确通过存在一个问题。我很确定它们现在可以通过空白,但是无论是HTML还是PHP,我都无法查明哪里出了错。我觉得我已经尝试了所有。无论如何,每次我提交正确的登录名时,都会得到“成功登录!”但是。$ row ['user']却什么也没显示。当我尝试显示错误时,不会显示错误,$ user或$ pass变量也不会显示。

有指针吗?谢谢!

HTML

<form class="form-signin" action="php/login.php" method="POST">
    <h2 class="form-signin-heading orange">Please Sign In</h2>
    <label for="user" class="sr-only">Username</label>
    <input type="text" name="user" class="form-control" placeholder="Username" required autofocus>
    <label for="pass" class="sr-only">Password</label>
    <input type="password" name="pass" class="form-control" placeholder="Password" required>
    <div class="checkbox">
      <label>
        <input type="checkbox" value="remember-me"> Remember Me
      </label>
    </div>
    <button id="form_button" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
  </form>

` PHP

<?php

// get values from login.html via POST
$user = $_POST['user'];
$pass = $_POST['pass'];

// prevent SQL injections
$user = stripcslashes($user);
$pass = stripcslashes($pass);
$user = mysqli_real_escape_string($user);
$pass = mysqli_real_escape_string($pass);

// connect to db and select db
$host_name = 'secrethost';
$database = 'secretdb';
$user_name = 'secretname';
$password = 'secretpassword';
$conn = mysqli_connect($host_name, $user_name, $password, $database);

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

// query db for login
$result = mysqli_query($conn,"SELECT * FROM logins WHERE user = '$user' AND pass = '$pass'")
                        or die("Failed to query db ".mysqli_error());

$row = mysqli_fetch_array($result);

if ($row['user'] == $user && $row['pass'] == $pass ){
        echo "Login successful!! Welcome ".$row['user'];
    } else {
    echo "Failed to login!";
}
$conn->close();?>

1 个答案:

答案 0 :(得分:-1)

找到了他们,

必须将$ conn变量移到PHP页面的顶部,并且缺少mysqli_real_escape_string()必需的$ conn变量。

固定代码如下

// connect to db and select db here
$conn = mysqli_connect($host_name, $user_name, $password, $database);

// get values from login.html via POST
$user = $_POST['user'];
$pass = $_POST['pass'];

// prevent SQL injections
$user = stripcslashes($user);
$pass = stripcslashes($pass);
$user = mysqli_real_escape_string($conn, $user);
$pass = mysqli_real_escape_string($conn, $pass);