mysql
2013-01-23 141 views 1 likes 
1

如何構建此查詢驗證,以便它獨立驗證電子郵件和密碼。因此,如果用戶輸入了正確的電子郵件,那麼位置(請參閱代碼)將與用戶輸入正確的密碼但輸入錯誤的電子郵件有所不同?這裏的查詢,如果SET語句是在出現錯誤變量:MySQL條件檢查

$mysql = mysql_query("SELECT * FROM employees WHERE email = '{$email}' AND hashed_password = '{$hashed_password} '"); 

if (mysql_num_rows($mysql) < 1) 
{ 
    header ("Location: index.php?error=1"); 
    die();  
} 
+0

是電子郵件和hashed_pa​​ssword每個獨特之處? –

回答

1
SELECT hashed_password = '{$hashed_password}' AS is_password_correct 
FROM employees WHERE email = '{$email}' 

如果沒有與$ email匹配的條目,此查詢將返回零行。

如果有一行匹配$ email,查詢將返回1或0,這取決於select-list中的布爾相等比較是true還是false。

然後,您可以根據三種可能的狀態在應用中執行不同的操作。

您應該停止在PHP中使用棄用的「mysql」函數,它們將在下一版本的PHP中消失。使用mysqli或PDO。

此外,您應該學習使用準備好的查詢並將$ hashed_pa​​ssword和$ email作爲查詢參數。然後,您可以避免SQL注入漏洞,而不必擔心轉義字符串。

這裏有一個完整的示例(未經測試)與PDO:

$stmt = $pdo->prepare("SELECT hashed_password = :password AS is_password_correct 
    FROM employees WHERE email = :email"); 
if ($stmt === false) { 
    // always check for errors 
} 
$result = $stmt->execute(array(":password"=>$hashed_password, ":email"=>$email)); 
if ($result === false) { 
    // always check for errors 
} 
if ($stmt->rowCount() == 0) { 
    // no such user 
} else { 
    while ($row = $stmt->fetch()) { 
     if ($row["is_password_correct"] == 1) { 
      // password is correct for the given user 
     } else { 
      // password is wrong 
     } 
    } 
} 
+0

ok @bill - 我在哪裏添加其他語句{ \t \t \t $ _SESSION ['loggedin'] =「YES」; //設置它以便用戶登錄! $ _SESSION ['email'] = $ email; //創建它可以通過$ _SESSION ['name']調用用戶名 $ _SESSION ['password'] = $ hashed_pa​​ssword; //創建它可以通過$ _SESSION ['name']調用用戶名 header(「Location:employee_profile.php」); //在這裏殺死腳本,所以它在登錄後不會顯示登錄表單! \t \t \t} – user1315367

+0

在哪裏我添加了評論'/ /密碼是正確的給定的用戶',那麼你知道電子郵件和密碼進行身份驗證。你可以做你需要記錄他們登錄的事實。 –

+0

困惑 - 我認爲我沒有把它設置正確。我完全刪除了舊的mysql_query,並將其替換爲你的。頁面加載但是當表單提交時,我得到一個配置錯誤。 – user1315367

0

這樣做的一個簡單的方法是使用一個OR條款,而不是AND做在PHP端的比較:

$mysql = mysql_query("SELECT email, hashed_password FROM employees WHERE email = '{$email}' OR hashed_password = '{$hashed_password} '"); 

if (mysql_num_rows($mysql) < 1) 
{ 
    // e-mail and password not found 
    header ("Location: index.php?error=1"); 
    die();  
} 
else 
{ 
    $rows = mysql_fetch_assoc($mysql); 

    if ($rows["email"] != $email) 
    { 
     // e-mail not found 
    } 
    else if ($rows["hashed_password"] != $hashed_password) 
    { 
     // passwords do not match 
    } 

} 
相關問題