我的原帖是:value in database 'members' shows a link when user is an admin 但我有一种感觉,我在这里完全错误地连接到我试图实现的结果。
1 <?php
2 include 'db_connect.php';
3
4 $results = mysqli_query($conn,"SELECT * FROM member");
5 $row = mysqli_fetch_array($results);
5 if($row['admin'] == "YES"){ echo "Admin"; }else{ echo "NOT admin.";}
7 ?>
问题是,我使用不具备管理员权限的人登录,在页面上看到ADMIN。我可能在这里做了一个错误的代码,我试着理解我做错了什么,但我只是看不到它......
现在我也意识到我有一个在后台运行的会话,看看是谁,我也在屏幕上显示该用户,如:欢迎 NameUser
1 ob_start();
2 session_start();
3
4 $username = $_POST['username'];
5 $password = $_POST['password'];
6
7 $conn = mysqli_connect('****', '****', '****', '****');
8
9 $username = mysqli_real_escape_string($conn, $username);
10 $query = "SELECT id, admin, username, password, salt
11 FROM member
12 WHERE username = '$username';";
13
14 $result = mysqli_query($conn, $query);
15
16 if(mysqli_num_rows($result) == 0) // User not found. So, redirect to login_form again.
17 {
18 header('Location: login.php');
19 }
20
21 $userData = mysqli_fetch_array($result, MYSQL_ASSOC);
22 $hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
23
24 if($hash != $userData['password'])
25 {
26 header('Location: login.php');
27 }else {
28 session_regenerate_id();
29 $_SESSION['sess_user_id'] = $userData['id'];
30 $_SESSION['sess_username'] = $userData['username'];
31 $_SESSION['sess_admin'] = $userData['admin'];
32 session_write_close();
33 header('Location: home.php');
34 }
35 }
我是否还需要更改$ sessions以使我的代码正常工作以及如何执行此操作,或者在后台运行会话时获取全新方法以获取该链接时他/她是管理员?
答案 0 :(得分:0)
如果您将admin存储在会话中使用:
if ($_SESSION['sess_admin']=="YES"){ echo "Admin"; }else{ echo "NOT admin.";}
答案 1 :(得分:0)
如注释中所述,第一个代码块中没有WHERE子句。因此,您已验证用户存在且密码有效,然后将其重定向为“主页”,但在显示页面时您不会选择特定用户。像下面这样的东西应该有效 -
<?php
include 'db_connect.php';
$results = mysqli_query($conn,"SELECT * FROM member WHERE id = '".$_SESSION['sess_user_id']."'");
$row = mysqli_fetch_array($results);
if($row['admin'] == "YES"){ echo "Admin"; }else{ echo "NOT admin.";}
?>
或者如Alex所述 - 您已经选择了用户管理状态并将其存储在会话中 - 因此,如果您需要检查所有内容,则无需再次访问数据库。