2017-01-26 236 views
-1

我做了一個登錄頁面,旨在讓我訪問user.php或admin.php取決於電子郵件和密碼。 我有一個數據庫(phpmyadmin)與2個用戶。我添加了一個布爾字段「type」(0表示普通用戶,1表示admin)。與管理員或用戶登錄php

這裏是我的PHP代碼:

<?php 
session_start(); 
$mysqli = new mysqli("localhost", "root", "", "database"); 
if ($mysqli->connect_errno) { 
    echo "Echec lors de la connexion à MySQL : (".$mysqli->connect_errno.") ".$mysqli->connect_error; 
} 
if (isset($_POST['submit'])) { 
    $email = $_POST['email']; 
    $password = $_POST['password']; 

    if ($email == "" || $password == "") { 
     echo '<div id ="errormsg">Please fill in all fields</div>'; 
    } else { 
     $query = mysqli_query(
      $mysqli, 
      "SELECT * FROM client WHERE email = '$email' and password = '$password' and type = 1 " 
     ) or die ("Can't query the database"); 
     $count = mysqli_num_rows($query); 

     if ($count == 1) { 
      if ($type == 1) { 
       $_SESSION['email'] = $email; 
       header("location: admin.php"); 
      } else { 
       if ($type == 0) { 
        $_SESSION['email'] = $email; 
        header("location: user.php"); 
       } else { 
        echo '<div id="errormsg">No matches, try again</div>'; 
       } 
      } 
     } 
    } 
} 

當我鍵入管理員的電子郵件地址和密碼,我會被重定向到user.php的,而不是admin.php的。當我輸入普通用戶的電子郵件和密碼時,什麼都沒有發生,同一頁面(login.php)刷新

+0

您的查詢失敗,您需要檢查真正的錯誤。 *「無法查詢數據庫」*沒有幫助你。 –

+0

此錯誤消息的詳細信息是什麼? –

+0

你好,歡迎來到SO。訪問http://bobby-tables.com瞭解更多關於SQL注入以及如何防止它們的信息。你編碼的方式(直接在查詢中使用'$ _POST')根本就不安全!您的數據庫可能會在幾秒鐘內被黑客入侵。 – Twinfriends

回答

0

我認爲$type不是if語句的有效代碼嘗試使用$ email,如果有工作並且您有許多用戶嘗試選擇再次驗證該用戶是否爲管理員或用戶admin.php,user.phplogin.php錯誤的用戶名和密碼。

<?php 
     session_start(); 
     $mysqli = new mysqli("localhost", "root", "", "database"); 
    if ($mysqli->connect_errno) { 
     echo "Echec lors de la connexion à MySQL : (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; 
    } 
     if (isset($_POST['submit'])) 
    { 
     $email = $_POST['email']; 
     $password = $_POST['password']; 

     if($email == "" || $password == "") 
     { 
      echo '<div id ="errormsg">Please fill in all fields</div>'; 
     } 

     else 
     { 
      $query = mysqli_query($mysqli, "SELECT * FROM client WHERE email = '$email' 
      and password = '$password' and type = 1 ") or die ("Can't query the database"); 
      $count = mysqli_num_rows($query); 

      if($count == 1) 
      { 
       if ($email == '[email protected]') 
       { 
        $_SESSION['email'] = $email; 
        header("location: admin.php"); 
       } 
       else if ($email == '[email protected]') 
       { 
        $_SESSION['email'] = $email; 
        header("location: user.php"); 
       } 
       else 
       { 
        echo '<div id="errormsg">No matches, try again</div>'; 
       } 
      } 
     } 
    } 

    ?> 
+0

感謝馬克這工作!但我想我的數據庫中存在的用戶連接並被重定向到user.php,同時管理員admin.php不僅是[email protected]和[email protected] – Darkimo