如何在php中添加用户角色

时间:2018-01-28 08:55:58

标签: php mysql

我尝试将我的用户和管理员重定向到某些特定页面,但我的php代码将管理员和用户重定向到同一页面

if (isset($_POST['Login'])) {
    $username = $_POST['username'];
    $password = $_POST['surname'];
    $password_hash = md5($password);
    $role;
    if (!empty($username) && (!empty($password))) 
    {
    $query = "SELECT 'id' FROM users WHERE 'staffno' = '$username' AND 'password'='$password_hash'";
    $run = mysqli_query($conn, $query);

    if ($run) {
         $sql = "SELECT users.role FROM users";
          $result = mysqli_query($conn, $sql); 
          $user = mysqli_fetch_array( $result);
          //$_SESSION['admin'] = $user['admin']; 
          $_SESSION['role'] = "admin";
        if((isset($_SESSION['role']) && $_SESSION['role'] == "admin")){
            header("location: Upload.php");
        }else{
            header("location: Home.php");
        }

    }

5 个答案:

答案 0 :(得分:1)

尝试使用它:

<a href="{{ route('brack.show', $users->BrackID) }}">Plačiau</a>

答案 1 :(得分:0)

我假设,你的会话是从顶部开始的。因为,你有硬编码$_SESSION['role']变量

$_SESSION['role'] = "admin";

而且,这总是如此

if((isset($_SESSION['role']) && $_SESSION['role'] == "admin")){

您需要改为使用

$_SESSION['role'] = $user['role']; 

答案 2 :(得分:0)

您需要在会话中存储动态用户角色

 $_SESSION['role'] = "admin";

更改为

 $_SESSION['role'] = $user['Your_User_Role_coulmn_name'];

此脚本$user = mysqli_fetch_array( $result);将返回有关所选用户的所有信息,因此,如果要将用户角色存储在同一个表中,则可以将用户角色值存储在会话中。这样,你的if语句就可以按照要求运行。

另外,对于使用会话,您需要在使用session_start()之前添加$_SESSION

请查看示例

session_start();
      if (isset($_POST['Login'])) {
      $username = $_POST['username'];
      $password = $_POST['surname'];
      $password_hash = md5($password);
      $role;
      if (!empty($username) && (!empty($password))) 
      {
      $query = "SELECT `id` FROM users WHERE `staffno` = '$username' AND `password`='$password_hash'";
      $run = mysqli_query($conn, $query);

          if ($run) {
               $sql = "SELECT users.role FROM users";
                $result = mysqli_query($conn, $sql); 
                $user = mysqli_fetch_array( $result);
                $_SESSION['role'] = "admin"; // this approach will be always same
                $_SESSION['role'] = $user['Your_User_Role_coulmn_name']; // you need to store dynamic user role into the session
              if((isset($_SESSION['role']) && $_SESSION['role'] == "admin")){
                  header("location: Upload.php");
              }else{
                  header("location: Home.php");
              }
            }
        }

     } 

答案 3 :(得分:0)

首先,您可以将unlukcy-13.jpg更改为$password = $_POST['surname'];,看看它是否能解决您的问题。

答案 4 :(得分:0)

尝试

if($run){
  $_SESSION['role'] = $user['role'];
   If($user['role'] ==  'admin'){ //admin page}else{//the other page}
}

还可以尝试通过添加

来限制第一个查询的结果

LIMIT 0, 1

您的代码现在甚至很短