-1

So basically i am able to set a session variable for username once a user logs in however i also need to set one based on if they are an admin or not. This is found in the "role" column in the users table. Every time i log in it seems that no one is an admin however, i have tried something like the below...

    <?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");
      }
    }
  }

To test this code i have a nav bar where i want certain tites availble depending on if the users role is an admin or not.

    <!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
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
JARLAUGH
  • 9
  • 5

1 Answers1

-1

$role = mysqli_query($db,$query2); This line returns a object from your database instead of string, to fix this problem, you have to grap the real value of the role from that resultset. this part of code must be changed to:

$result = mysqli_query($db,$query2);

if( $result){
 $row = mysqli_fetch_array($result);
 $role= $row["role"];
 $_SESSION['role']= $role;
}
Hardood
  • 503
  • 1
  • 5
  • 15