2014-07-21 76 views
0

我是初學者,我正在努力學習。我使用php,mysqli創建簡單的登錄表單。我已經創建了需要它的所有信息的數據庫。我選擇了bellow php代碼嘗試在我的頁面上登錄用戶,但是發生的事情是,在輸入正確的電子郵件和密碼後,它只是將我帶回到同一頁面(index.php),就好像它看起來信息不正確,但我知道就像我把它們放在數據庫中一樣,它只是不想把我帶到下一頁(home.php)。有人可以看看我的代碼,看看我做錯了什麼。謝謝。用PHP和mysqli創建登錄表單

登錄形式(的index.php):

<form id="form" method="post" action="login_process.php"> 
<input type="text" name="email" size="15" placeholder="email" required="required" /> 
<input type="password" name="password" size="15" placeholder="Password" required="required" /> 
<input id="loginButton" type="submit" name="submit" value="LOGIN" /> 
</form> 

db_config.php:

define("DBHOST", "localhost"); 
define("DBUSER", "root"); 
define("DBPASS", ""); 
define("DBNAME", "aroundtheworld"); 

login_process.php:在字符串

require("db_config.php"); 

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

$conn = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME); 

$email = mysqli_real_escape_string($conn, $email); 
$query = "SELECT * FROM users WHERE email = '$email'"; 

$result = mysqli_query($conn, $query); 

if(mysqli_num_rows($result) == 0){ 
    header("Location: index.php"); 
} 

$userData = mysqli_fetch_array($result, MYSQL_ASSOC); 
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password)); 

if($hash != $userData['password']){ 
    header("Location: index.php"); 
}else{ 
    header("Location: home.php"); 
} 
+0

請開始使用PDO和準備語句。 嘗試逐步調試您從mysqli_num_rows獲得的內容。 –

+0

@ dariusz.g PDO不是強制性的,mysqli是可以的...... – Sugar

+0

如果您使用mysqli_error()檢查錯誤將會很好。 –

回答

2

你不能只用變量,你需要將它們鏈接在一起。

所以你

"SELECT * FROM users WHERE email = '$email'"; 

必須

"SELECT * FROM users WHERE email = " . $email; 

但這是不安全的,不好的做法!

你非常頑固到SQL Injection!您需要至少使用Prepared Statements。從鏈接

採取這是一個例子,如何寫這樣querys

$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)"); 
$stmt->bindParam(':name', $name); 
$stmt->bindParam(':value', $value); 

// insert one row 
$name = 'one'; 
$value = 1; 
$stmt->execute(); 
+0

感謝您的信息,我會更多地查看此信息。我也修正了Janaka的建議,現在我可以處理到下一頁(home.php),即使我把不正確的密碼。如果($ hash!= $ userData ['password']){header(「Location:home .php「);} else {header(」Location:index。());} – Ronin

+0

你是否從你的選擇中得到結果?或者它是空的? – KhorneHoly

+0

我不知道我是否理解。在我把電子郵件和密碼後,它需要我到我想要的頁面(home.php)但它會帶我到下一頁,即使我把不正確的電子郵件和密碼。我期待後不正確的信息,讓我回到登錄頁面(index.php)。 – Ronin