我对php和数据库有点陌生。我开发了一个基于角色的访问web应用程序。这个场景是我有两个表
- tbl_user
columns -> user_id, username, school_id (school_id是外键)
- tbl_school
columns -> school_id, school_name
只有两个角色
管理,用户
用户将基于学校,一旦用户将生成,学校名称将与用户名相关联;user_id
现在我可以显示id,不管是admin还是user
但是一旦用户登录,我希望显示相关的学校名称而不是角色名称。
将非常感谢您的帮助
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; ? >
好吧,这只是一个基于我阅读你的问题的快速建议。
所以你可以问你的问题的数据库…即给我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相关的学校名称
明白了吗?