2017-04-11 109 views
1

我有一個名爲「禁止」以0值,如果他們不是一個MySQL列,和值1,如果是這樣,這是內部表「用戶」。目前這段代碼給出了一個錯誤「不正確的用戶名/密碼組合!」如果一個人是被禁止的,但是我無法弄清楚如何得到它說「你被禁止」如果「禁止」的值是1。登錄系統,用戶禁止PHP

<?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!"; 
     } 
    } 

} 

?> 
+0

它通常是消除東西是個好主意' === FALSE'而是翻轉,要成爲'如果($用戶)'和反向的塊的順序。 – tadman

回答

3

不要把禁止檢查查詢,讓查詢從數據庫中返回數據。然後檢查條件,如果禁用== 1,然後顯示用戶被禁止的錯誤。所以,你的代碼應該是像這樣:

$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 
    } 
0

它看起來像你只需要一個「否則,如果」中間還有...

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 {