0
if(isset($_SESSION['admin'])) {
echo "<li><b>Admin</b></li>";
}

<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();

$conn = blah blah
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
$result2 = $conn->query($query2);
if($result2->num_rows==1) {
$_SESSION['admin'] = $result2;
}
?>

嗨,我正在尝试设置此会话变量,但似乎没有设置,我想知道是否有人可以提供帮助。如果 session['admin'] isset 它应该回显管理按钮。但我不太确定为什么?(我确实有会话开始和每个页面上的所有内容,这不是问题或任何“你没有 php 标签”我已经检查了 mysql 查询,它确实从我的表中返回了一些东西。有什么想法吗?

4

2 回答 2

4

在与会话变量有关的任何事情之前,您session_start();应该位于页面顶部。

文档

当 session_start() 被调用或会话自动启动时,PHP 将调用打开和读取会话保存处理程序。

从评论编辑:

<?php
    session_name('MYSESSION');
    session_set_cookie_params(0, '/~cgreenheld/');
    session_start();
    // Moved to start after answer was accepted for better readability
    // You had the <?php after this if statement? Was that by mistake?
    if(isset($_SESSION['admin'])) 
    {
        echo "<li><b>Admin</b></li>";
    }

    // If you have already started the session in a file above, why do it again here?

    $conn = blah blah;
    $query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
    // Could you echo out the above statement for me, just to 
    // make sure there aren't any problems with your sessions at this point?
    $result2 = $conn->query($query2);
    if($result2->num_rows==1) 
    {
        $_SESSION['admin'] = $result2;
        // It seems you are trying to assign the database connection object to it here.
        // perhaps try simply doing this:
        $_SESSION['admin'] = true;
    }
?>

从进一步的评论中编辑 2:

您必须像这样实际获取获取数据 - 从本教程中截取,这可能会帮助您更多:

$query  = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);

while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    echo "Name :{$row['name']} <br>" .
     "Subject : {$row['subject']} <br>" .
     "Message : {$row['message']} <br><br>";
} 

但是话虽如此,当我们在谈论它时,最好不要使用旧mysql_*功能并转向更好的PDO

于 2012-08-23T08:32:43.730 回答
1

移动session_start();到页面顶部。您正在尝试检索未加载的会话。

编辑:尝试 echoing $_SESSION['admin'],如果它甚至包含一些东西。if($result2->num_rows==1)还尝试通过添加echo('its working');或在其中调试代码die('its working');,以检查 $result2 是否恰好包含 1 行,因为目前似乎 $result2 包含多于 1 行或根本没有行。

于 2012-08-23T08:32:55.083 回答