2014-07-22 92 views
0

我試圖在php中建立一個與mysql數據庫連接的登錄頁面。下面是登錄頁面的html代碼,其中輸入了值,然後定向到第二個在那裏他們被檢查PHP的頁面..

<html> 
<head> 
    <title>Library Login</title> 
    <link rel="stylesheet" type="text/css" href="css/reset.css"> 
    <link rel="stylesheet" type="text/css" href="css/structure.css"> 
</head> 
<body> 
    <form class="box login" method="GET" action="http://localhost/redirect.php"> 
     <label align="center"><font size="6" color="grey">Library System</font></label> 
     <fieldset class="boxBody"> 
     <label>Username</label> 
     <input type="text" placeholder="Username" required name="username"> 
     <label><a href="#" class="rLink" tabindex="5" ></a>Password</label> 
     <input type="password" placeholder="Password" required name="password"> 
     <input type="submit" class="btnLogin" value="Login" name="login"> 
     <input type="reset" class="btnLogin" value="Reset" name="reset" > 
     <label> 
    </form> 
</html> 
</div> 

及以下就是隻執行else條件的任何條目輸入第二個頁面的代碼...我是新來的PHP和MySQL ......請大家幫幫我out ...

<?php 
$con=mysqli_connect("localhost","root","","project"); 

if(mysqli_connect_errno()) 
{ 
    echo "failed".mysqli_connect_errno(); 
} 

$uid=$_GET['username']; 
$pass=$_GET['password']; 
$sql="SELECT *FROM login"; 
$result=mysqli_query($con,$sql); 

while($data=mysqli_fetch_array($result)) 
{ 
    if($uid==$data['user'] and $pass==$data['pass']) 
    { 
     header('location:http://localhost/error/index.html'); 
    } 
    else 
    { 
     header('location:http://localhost/mam.html'); 
    } 
} 

mysqli_close($con); 
?> 
+0

沒有..每次其他條件執行時檢查值,而不管我輸入了正確的輸入或不是 – beginner

+0

我知道這不是一個答案,但你真的應該嘗試移動到[PDO](http:///php.net/manual/en/book.pdo.php)而不是mysqli。 – pid

+1

如果結果的第一行不匹配,那麼您將在else部分中並且使用header()調用您將離開mam.html並且不回到此腳本。您應該使用WHERE子句來獲取相關的行(如果存在)。而且,在將輸入值放入WHERE子句之前,應先閱讀有關佔位符的準備語句。 – VMai

回答

0

好吧,在您處理身份驗證時,讓我們稍微改進您的代碼。

<?php 

// Do not connect using root, especially when not setting a password: 
$con=mysqli_connect("localhost","projectuser","password","project"); 
if(mysqli_connect_errno()) 
{ 
echo "failed".mysqli_connect_errno(); 
} 

$uid = $_GET['username']; 
$pass = $_GET['password']; 

// This is the main problem, there was a typo: 
$sql = "SELECT * FROM login"; 

// Directly ask the DB if the credentials are correct. 
// Then you do not need the loop below. 
// BUT: Do not forget to escape the data in this case! 
$sql .= " WHERE uid = '" . mysqli_real_escape_string($uid) . "' AND pass = '" . mysqli_real_escape_string($pass) . "'"; 

$result=mysqli_query($con,$sql); 
if ($result->num_rows === 1) { 
    header('location:http://localhost/mam.html'); 
} else { 
    header('location:http://localhost/error/index.html'); 
} 
mysqli_close($con); 
?> 

進一步的改進是散列(和鹽)數據庫中的密碼。

另外,正如VMai指出的那樣,使用準備好的陳述將是適當的。

+1

'mysql_real_escape_string'這是一個'mysql_'函數;小心;-) –

+0

你在混合mysqli_ *函數(由OP使用)和mysql_ *函數。這是行不通的。請使用預處理語句和佔位符來改進mysqli行中的代碼,並將輸入綁定到佔位符而不是字符串連接。 – VMai

+0

錯過了我,修正了這個問題。但是,如果兩個模塊都可用 - 這至少可以用於逃跑。 – brainbowler