2012-01-25 185 views
2

我有一个评论页,我有用户角色(全局管理员(3),管理员(2),用户(1)),他们可以所有发表的评论在页面上。用户角色(例如管理员,用户)进入表而不是用户名

我的问题是用户角色(1,2或3)被放到表中而不是用户名,任何想法如何解决这个问题?这里是插入代码。

<? 
include 'dbconnect.php'; 
$userName = $_SESSION['user']; 
$comment = $_REQUEST["comments"]; 
$game_ID = $_SESSION['id']; 
$query = "INSERT INTO comments (userName, comment, page_ID) VALUES ('$userName',  '$comment', '$game_ID')"; 
mysql_query ($query); 
echo "Thanks, your comment has been added!"; 
include 'close.php'; 
?> 

登录代码:

$errorMessage = ''; 
if (!empty($_POST['txtuserName']) && !empty($_POST['txtpassword'])) { 
include 'dbconnect.php'; 


$user = $_POST['txtuserName']; 
$password = $_POST['txtpassword']; 

// check if the user id and password combination exist in database 
$query = "SELECT userName, password, role FROM member WHERE userName = '$user' AND password = '$password'"; 

$output = mysql_query($query) or die('Query failed. ' . mysql_error()); 
$row = mysql_fetch_array($output); 

if (mysql_num_rows($output) == 1 AND $row['role']==1) { 
    // the user id and password match, 
    // set the session 
    $_SESSION['user'] = true; 
    // after login we move to the main page 
    header('Location: games.php'); 
    exit; 
} 
elseif (mysql_num_rows($output) == 1 AND $row['role']==2) { 
    // the user id and password match, 
    // set the session 
    $_SESSION['admin'] = true; 
    $_SESSION['user'] = true; 
    // after login we move to the main page 
    header('Location: games.php'); 
    exit; 
} 
elseif (mysql_num_rows($output) == 1 AND $row['role']==3) { 
    // the user id and password match, 
    // set the session 
    $_SESSION['admin'] = true; 
    $_SESSION['user'] = true; 
    $_SESSION['global'] = true; 
    // after login we move to the main page 
    header('Location: listUsers.php'); 
    exit; 
} 
else { 
    $error = 'The supplied username and/or password was incorrect. Please try again.'; 
} 

include 'close.php'; 
} 
?> 

回答

1

只需将userName到会话:

$_SESSION['userName'] = $row['userName']; 

然后它会在你的应用的其余部分可用。

还请记住,您可以将数组放入会话中。所以,你可以重构你的代码为:在您的代码

$_SESSION['user'] = array('userName'=>$row['userName'], 'role'=>$row['role']); 

及更高版本:

if ($_SESSION['user']['role'] == 2) { 
    // allow admin stuff 
} 
1

你设置$_SESSION['user'] = true;但后来试图与$userName = $_SESSION['user'];访问它...您的登录代码应改为说

$_SESSION['user'] = $row['userName']; 

你的代码将$_SESSION['user']的值插入到userName的数据库中,但不幸的是,它只是将其设置为true当你登录

+0

这时候,你在我之前回答了我的打字! –

+0

工作过!多谢你们!需要更快的块Frederick哈哈:) –

相关问题