I have a mysql column named "banned" with value of 0 if they are not, and a value of 1 if they are, which is inside table "users." Currently this code gives a an error "Incorrect username/password combination!" if a person is banned however I cannot figure out how to get it to say "you are banned" if the value of "banned" is 1.
<?php
if(isset($_POST['submit'])){
session_start();
// configuration
$dbhost = "localhost";
$dbname = "login";
$dbuser = ".";
$dbpass = ".";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8mb4");
// new data
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$passwordAttempt = !empty($_POST['password']) ? trim($_POST['password']) : null;
// query
$result = "SELECT id, username, password, banned FROM users WHERE username= :username AND banned = '0'";
$stmt = $conn->prepare($result);
$stmt->bindValue(':username', $username);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if($user === false){
//Could not find a user with that username!
//PS: You might want to handle this error in a more user-friendly manner!
$error = "Incorrect username/password combination!";
} else{
//User account found. Check to see if the given password matches the
//password hash that we stored in our users table.
//Compare the passwords.
$validPassword = password_verify($passwordAttempt, $user['password']);
//If $validPassword is TRUE, the login has been successful.
if($validPassword){
$_SESSION['login_user'] = $username;
header("location: home.php");
exit;
} else{
$error = "Incorrect username/password combination!";
}
}
}
?>
Do not put a banned check in the query, let the query return the data from database. And then check for the condition if banned == 1 then show the error that the user is banned. So your code should be something like so:
$result = "SELECT id, username, password, banned FROM users WHERE username= :username";
$stmt = $conn->prepare($result);
$stmt->bindValue(':username', $username);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if($user === false){
$error = "Incorrect username/password combination!";
} else{
if($user['banned'] == '1')
{
//give the banned error and return;
}
else
{
//Do the login stuff
}
It looks like you just need an "else if" in the middle there...
if($user === false){
//Could not find a user with that username!
//PS: You might want to handle this error in a more user-friendly manner!
$error = "Incorrect username/password combination!";
} else if ($user['banned'] == 1){
$error = "Hey! You are banned";
} else {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.