1

如何构建此查询验证,以便它独立验证电子邮件和密码。因此,如果用户输入正确的电子邮件,位置(见代码)将不同于用户输入正确的密码但错误的电子邮件?这是查询,if 语句设置为 GET 错误变量:

$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();    
} 
4

2 回答 2

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

如果没有匹配 $email 的此类条目,此查询将返回零行。

如果存在与 $email 匹配的行,则查询将根据选择列表中的布尔相等比较是真还是假而返回 1 或 0。

然后,您可以根据三种可能的状态在您的应用程序中执行不同的操作。

您应该停止在 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
        }
    }
}
于 2013-01-23T22:48:18.830 回答
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
    }

}
于 2013-01-23T22:44:09.993 回答