我有一个评论页面,我有用户角色(全局管理员(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';
}
?>
答案 0 :(得分:1)
您正在设置$_SESSION['user'] = true;
但稍后尝试使用$userName = $_SESSION['user'];
访问它...您的登录代码应改为
$_SESSION['user'] = $row['userName'];
您的代码正在将$_SESSION['user']
的值插入到userName
的数据库中,但不幸的是,它只是在您登录时将其设置为true
。
答案 1 :(得分:1)
只需将userName
放入会话:
$_SESSION['userName'] = $row['userName'];
然后,它将在您的其他应用程序中提供。
另请注意,您可以将数组放入会话中。因此,您可以将代码重构为:
$_SESSION['user'] = array('userName'=>$row['userName'], 'role'=>$row['role']);
稍后在您的代码中:
if ($_SESSION['user']['role'] == 2) {
// allow admin stuff
}