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;
}
?>
嗨,我正在尝试设置此会话变量,但它似乎没有设置,我想知道是否有人可以提供帮助。如果会话['admin'] isset,它应该回显管理按钮。 但我不太清楚为什么? (我确实有会话开始和每个页面上的所有内容,这不是问题或任何“你没有php标签”我检查了mysql查询,它确实从我的表返回一些东西。有什么想法吗?
答案 0 :(得分:4)
在与会话变量有任何关系之前,您的session_start();
应位于页面顶部。
来自the docs:
当调用session_start()或会话自动启动时,PHP将调用open和read会话保存处理程序。
从评论中编辑:
<?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:
你必须实际获取这样的数据 - 从this tutorial剪切,这可能会帮助你更多:
$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,这样会好得多。
答案 1 :(得分:1)
将session_start();
移至页面顶部。您正在尝试检索未加载的会话。
编辑:如果它甚至包含某些内容,请尝试回显$_SESSION['admin']
。同时尝试通过在其中添加if($result2->num_rows==1)
或echo('its working');
来调试die('its working');
代码,以检查$ result2是否包含正好1行,因为目前似乎$ result2包含多于1行或不包含完全没有行。