我对php和数据库有点新鲜。我开发了基于角色的访问Web应用程序。场景是我有2张桌子
列 - > user_id,username,school_id(school_id是外键)
列 - > school_id,school_name
只有2个角色
管理员用户
一旦用户将被生成,用户将基于学校,学校名称将与用户名& USER_ID
现在我可以显示id,无论是管理员还是用户
但是一旦用户登录,我希望显示关联的学校名称而不是角色名称。
非常感谢帮助
的index.php
$errors = array(
1=>"Invalid user name or password, Try again",
2=>"Please login to access this area"
);
$error_id = isset($_GET['err']) ? (int)$_GET['err'] : 0;
if ($error_id == 1) {
echo '<p class="text-danger">'.$errors[$error_id].'</p>';
}elseif ($error_id == 2) {
echo '<p class="text-danger">'.$errors[$error_id].'</p>';
}
?>
<form action="authenticate.php" method="post" role="form">
<div class="form-group">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text" class="form-control" required autofocus></div>
<div class="form-group">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password" class="form-control" required></div>
<input name="submit" type="submit" value=" Login " class="btn btn-primary btn-lg btn-block">
</form>
AUTHENTICATE.PHP
<?php
require 'database-config.php';
session_start();
$username = "";
$password = "";
if(isset($_POST['username'])){
$username = $_POST['username'];
}
if (isset($_POST['password'])) {
$password = $_POST['password'];
}
$q = 'SELECT * FROM tbl_user WHERE username=:username AND password=:password';
$query = $dbh->prepare($q);
$query->execute(array(':username' => $username, ':password' => $password));
if($query->rowCount() == 0){
header('Location: index.php?err=1');
}else{
$row = $query->fetch(PDO::FETCH_ASSOC);
session_regenerate_id();
$_SESSION['sess_user_id'] = $row['id'];
$_SESSION['sess_username'] = $row['username'];
$_SESSION['sess_userrole'] = $row['role'];
echo $_SESSION['sess_userrole'];
session_write_close();
$multirole = $row['role'];
switch ($multirole) {
case "admin":
header('Location: dashboard.php');
break;
case "user":
header('Location: user_dashboard.php');
break;
default:
echo "No User Found ! Please Contact Admin";
}
}? >
DASHBOARD.PHP
<?php
session_start();
$role = $_SESSION['sess_userrole'];
if(!isset($_SESSION['sess_username']) || $role!="admin"){
header('Location: index.php?err=2');
}
? >
html......
Welcome : <?php echo $role; ? >
答案 0 :(得分:0)
根据我对你的问题的解读,这只是一个快速的建议。
所以你可以问你对数据库的问题......即 给我一个user_id所在的学校名称。你会做类似的事情(这不是经过测试的代码......)
$q = 'SELECT u.username,s.school_name FROM tbl_user u
JOIN tbl_school s ON u.school_id = s.school_id
WHERE u.user_id=:user_id';
你只需要给它正确的user_id,你可以弄清楚。
所以这是询问,给定user_id(你已经知道)给我在tbl_school中的学校名称,该名称与user_id的用户表中的school_id相关。
这有意义吗?