根据数据库值设置会话变量

因此,基本上,我能够在用户登录后为用户名设置会话变量,但是我还需要根据他们是否是管理员来设置一个会话变量。这可以在用户表的“角色”列中找到。每次我登录时,似乎没有人是管理员,但是我尝试了以下类似的操作...

    <?php
  session_start();

  $username = "";
  $email = "";
  $role= "";
  $errors = array();

//connect to db
$db = mysqli_connect('localhost', 'root', '', 'jmervyn');

    ...



    //log user in for login Page
  if (isset($_POST['login'])){
    $username = mysqli_real_escape_string($db, $_POST['username']);
    $password = mysqli_real_escape_string($db,$_POST['password']);

    //ensure that form fields are filled correctly
    if (empty($username)){
      array_push($errors,"Username is required");
    }
    if (empty($password)){
      array_push($errors,"Password is required");
    }

    $query2 = "SELECT role FROM users WHERE username = '$username'";
    $role = mysqli_query($db,$query2);

    if (count($errors) == 0){
      $password = md5($password); // encrypt password before comparing with database
      $query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
      $result = mysqli_query($db,$query);
      if (mysqli_num_rows($result)==1){
        // log in users
        $_SESSION['username']= $username;
        $_SESSION['role']= $role;
        $_SESSION['success']="You are now logged in";
        header('location: index.php'); //redirect to home page
      }else{
        array_push($errors, "Wrong username/password combination");
      }
    }
  }

为了测试此代码,我有一个导航栏,在该栏中我希望某些站点可用,具体取决于用户角色是否为管理员。

    <!DOCTYPE html>
<html>
<header>
<h1 class="Training Planner">Training Planner</h1>
<input type="checkbox" id="nav-toggle" class="nav-toggle">
<nav>
  <?php
      if($_SESSION['role'] == "admin") {
      ?>
      <ul class="nav navbar-nav">
        <li><a href="index.php">Home</a></li>
        <li><a href="calendar.php">Calendar</a></li>
        <li><a href="map.php">Map</a></li>
        <li><a href="gyms.php">Gyms</a></li>
      </ul>

      <?php } else { ?>
          <ul class="nav navbar-nav">
            <li><a href="index.php">Home</a></li>
            <li><a href="calendar.php">Calendar</a></li>
            <li><a href="map.php">Map</a></li>
          </ul>
      <?php
      }
  ?>

    enter code here
评论