PHP - mySQL查询将结果作为会话变量无效

时间:2018-04-10 23:25:19

标签: php mysql

在将SQL Query的结果作为变量传递而不是作为跨所有页面的会话时,我遇到了问题。

我目前将“用户名”作为会话传递并且有效,但我尝试将“权限级别”设置为完全相同的会话,但是当“用户名”执行时,这不起作用。< / p>

我已经在phpmyadmin中对数据库中的mySQL查询进行了测试,并且它运行正常,任何有关此问题的帮助都会得到认可,因为我已经绕圈子了。

SELECT privledge_lvl FROM `users` WHERE username='$username'

结果:

|privledge_lvl|
---------------
|2            |

的login.php

<?php
        require('db.php');
        session_start();
    // If form submitted, insert values into the database.
    if (isset($_POST['username'])){

                $username = stripslashes($_REQUEST['username']); // removes backslashes
                $username = mysqli_real_escape_string($con,$username); //escapes special characters in a string
                $password = stripslashes($_REQUEST['password']);
                $password = mysqli_real_escape_string($con,$password);

        //Checking is user existing in the database or not
        $query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";
                $result = mysqli_query($con,$query) or die(mysqli_error());
                $rows = mysqli_num_rows($result);

        $privquery = "SELECT privledge_lvl FROM `users` WHERE username='$username'";
                $privresult = mysqli_query($con,$privquery) or die(mysqli_error());

        if($rows==1){

                        $_SESSION['username'] = $username;
                        $_SESSION['privledgelvl'] = $privresult;
                        header("Location: index.php"); // Redirect user to index.php
            }else{
                                echo "<div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
                                }
    }else{
?>

auth.php

<?php
session_start();
if(!isset($_SESSION["username"])){
header("Location: login.php");
exit(); }
?>

的index.php

<p>Welcome <?php echo $_SESSION['username']; ?>!</p>
<p>Privledge Level <?php echo $_SESSION['privledgelvl']; ?></p>

1 个答案:

答案 0 :(得分:0)

您应该从尝试将mysqli_result对象(mysqli_query的返回值)转换为此行上的字符串时收到PHP警告:

<?php echo $_SESSION['privledgelvl']; ?>

您应该使用

设置$ _SESSION ['privledgelvl']
$row = $privresult->fetch_assoc();
// or, procedurally, $row = mysqli_fetch_assoc($privresult);
$_SESSION['privledgelvl'] = $row['privledgelvl'];

或者 - 正如所指出的那样 - 您可以从第一个查询中获取它而不用第二个查询:

$row = $result->fetch_assoc();
// or, procedurally, $row = mysqli_fetch_assoc($result);
$_SESSION['privledgelvl'] = $row['privledgelvl'];