PHP检查用户是否为Admin [重复]

This question already has an answer here:

This is my first post.

I am trying to check with my MySQL Database to see if the user is a admin or a regular user, it always says that I am an admin. My database is:

id name email password role

I have a test user which is: id: 1 name: admin email: admin@admin.com role: 2

My code is:

<?php if (isset($_SESSION['usr_id']) || $row["role"] = 1) { ?>
<!DOCTYPE html>
<html>
<head>
<h2>You are a admin!</h2>
</head>
</html>
<?php } else { ?>
<h2>You are either not logged in, or you have no access to this page.</h2>
<?php } ?>

However, it always says that I am a admin even if my role is 2!

</div>

$row["role"] = 1 this is assignment, not comparison. Go for $row["role"] == 1

you're using the OR operator (||), the operator verifies compliance any of the 2 conditions are indicating in the IF statement, for this reason will display the message: "You are a admin!" when any of the 2 conditions is met. If you want the 2 conditions are met to show you that message must use the logical AND (&&) to verify the validity of the 2 conditions within your IF statement.

if (isset ($_SESSION ['usr_id']) && $row ["role"] = 1) { ... }

There must be 1 in session. Try again after destroy the session.

Also change the condition

FROM : <?php if (isset($_SESSION['usr_id']) || $row["role"] = 1) { ?>

TO : <?php if ((isset($_SESSION['usr_id']) && $_SESSION['usr_id'] == 1) || $row["role"] == 1) { ?>

Ok, it seems you are assigning the value instead of comparing it. That is the reason why you always log in as an administrator.

Just change $row["role"] = 1 by $row["role"] == 1. Furthermore, you should use the && operator instead of ||.

Finally, it seems you are learning programming for the first time, and these are typical mistakes that everyone who is programmer had at the beginning. I recommend you the book "PHP: A Beginner's Guide", by Vikram Vaswani, which is an excellent and easy guide for those who are learning to program in PHP.

Good luck.