2011-11-17 71 views
0

我有以下字段的MySQL表:PHP登錄不工作

ID 用戶名 密碼 作用

管理有一定的作用1號和普通用戶有一定的作用2號

<?php 
// we must never forget to start the session 
session_start(); 

$errorMessage = ''; 
if (isset($_POST['username']) && isset($_POST['password'])) { 
    include 'library/connect.php'; 

    $username = $_POST['username']; 
    $password = $_POST['password']; 

    // check if the user id and password combination exist in database 
    $sql = "SELECT role FROM user WHERE username = '$username' AND password = '$password'"; 

    $result = mysql_query($sql) or die('Query failed. ' . mysql_error()); 
    $row = mysql_fetch_array($result); 

    if (mysql_num_rows($result) == 1 AND $row['role']==2) { 
     // the user id and password match, 
     // set the session 
     $_SESSION['userame'] = true; 
     // after login we move to the main page 
     header('Location: login_success.php'); 
     exit; 
    } 
    elseif (mysql_num_rows($result) == 1 AND $row['role']== 1) { 
     // the user id and password match, 
     // set the session 
     $_SESSION['admin'] = true; 
     $_SESSION['username'] = true; 
     // after login we move to the main page 
     header('Location: admin.php'); 
     exit; 
    } 
else { 
     $errorMessage = 'Sorry, wrong user id/password <a href="login.html">Go Back</a>'; 
    } 

    include 'library/closedb.php'; 
} 
?> 



<?php 
if ($errorMessage != '') { 
?> 
<p align="center"><strong><font color="#990000"><?php echo $errorMessage; ?></font></strong></p> 
<?php 
} 
?> 

當管理員日誌,它工作正常並且被重定向到admin.php的,而當在正常用戶登錄,什麼都不會發生在所有的頁面只是得到刷新。我究竟做錯了什麼?

+3

**警告**此代碼易受** [SQL注入](http://en.wikipedia.org/wiki/SQL_injection)**影響。 – mellamokb

+2

我知道,不專注於secuirty atm – Jahed

+0

這是一個錯字在這裏或在您的代碼? '$ _SESSION ['userame'] = true;'不應該是$ _SESSION ['username']? –

回答

6

您在第一if塊拼寫錯誤的用戶名role=2

$_SESSION['userame'] = true;

+0

噢耶....silly我......謝謝:) – Jahed

4

看起來像一個錯字是原因:

$_SESSION['userame'] = true; 
0
$_SESSION['userame'] = true; 
to 
$_SESSION['username'] = true; 

如果不修復問題,您可以給login_success .php

if (mysql_num_rows($result) == 1 AND $row['role']==2) { 
     // the user id and password match, 
     // set the session 
     $_SESSION['username'] = true; 
     // after login we move to the main page 
     header('Location: login_success.php'); 
     exit; 
    } 
+0

你有點遲了:) –

+0

是的,它的第一天和第一反應幾乎不可能 –