会话使用不当?

时间:2017-09-14 08:40:39

标签: php mysql session

所以我在php中遇到代码问题,这让我发疯了...... 问题是,我正在制作登录页面,我有index.php,login.php和dashboard.php。 登录表单在index.php中,在login.php中它检查用户是否在数据库中,如果它是用户重定向到dashboard.php,但是当我输入正确的用户并通过时,它会将我重定向到index.php而不是仪表板.PHP ??

的login.php

<?php
session_start();
include($_SERVER['DOCUMENT_ROOT'] . "/new_cms/includes/db.php");

$username = $_POST['username'];
$password = $_POST['password'];
$btn = $_POST['submit'];

if(isset($btn)){
  if(empty($username) || empty($password)){
      echo "You must fill all fields";
  }else{
      $sql = "SELECT * FROM admins WHERE username = '$username' AND password = '$password'";
      $query = mysqli_query($dbconn, $sql);
      $rows = mysqli_num_rows($query);

      if($rows > 0){
           $_SESSION['usr'] = $rows['password'];
           header("Location: dashboard.php");
      }else{
           echo "Invalid login";
      }
   }
}
?>

dashboad.php

<?php 
session_start();
include($_SERVER["DOCUMENT_ROOT"] . "/new_cms/includes/db.php");
include($_SERVER["DOCUMENT_ROOT"] . "/new_cms/admin/login.php");

if(!isset($_SESSION['usr'])){
    header("Location: index.php");
}else{
    echo "Welcome";
}
?>

我做错了什么?

1 个答案:

答案 0 :(得分:1)

$ rows只是一个数字,而不是数组,因为你使用了mysqli_num_rows。你还是试着获得$ rows ['password']。

相反,获取结果的第一行并使用它来分配会话变量。

if(isset($btn)){
  if(empty($username) || empty($password)){
      echo "You must fill all fields";
  }else{
      $sql = "SELECT * FROM admins WHERE username = '$username' AND password = '$password'";
      $query = mysqli_query($dbconn, $sql);
      $rows = mysqli_num_rows($query);

      if($rows > 0){
           $user = mysqli_fetch_assoc($query);
           $_SESSION['usr'] = $user['password'];
           header("Location: dashboard.php");
      }else{
           echo "Invalid login";
      }
   }
}