-1

我之前问过一个类似的问题,但我想我现在更接近答案了。

我有一个功能可以在用户登录个人资料之前验证用户的电子邮件地址和密码。

如果电子邮件不正确,它会生成一条错误消息;它回显“未找到匹配的电子邮件”。

当我输入正确的电子邮件和密码时,什么都不会返回。但是,如果我随后输入错误的密码和错误的电子邮件,它会给我“找不到匹配的电子邮件”。正确的电子邮件但错误的密码也会发生同样的事情。

我试图返回,fetchAll但是fetchColum当我输入正确的值时,我仍然得到相同的循环。

有任何想法吗 ?

function valid_credientials($email,$password){
    global $db;

    $q = "SELECT * FROM user WHERE email = :email AND password =:password";
    $query = $db->prepare($q);
    $query->execute(array(":email" => $email, ":password" => $password));
    $results = $query->fetchAll();

    if($results !=FALSE && $query->rowCount() > 0) {
       if($results[0]['password'] == $password){
            $_SESSION['email'] = $email;
            return $query->fetchAll($q,0)==1 ? true:false;
        }
    }

    // return false by default
    return false;
}

邮局

if (isset($_POST['email'], $_POST['password'])) {
    if (valid_credientials($_POST['email'], $_POST['password']) == false) {
        $errors[] = 'No matching email found.';
    }

    if (empty($errors)) {
        $_SESSION['email'] = htmlentities($_POST['email']);
        header("Location: profile.php");
        die();
    }
}
4

2 回答 2

2

您应该添加一个默认return false;语句:

function valid_credientials($email,$password){
    global $db;

    $q = "SELECT * FROM user WHERE email = :email AND password =:password";
    $query = $db->prepare($q);
    $query->execute(array(":email" => $email, ":password" => $password));
    $results = $query->fetchAll();

    if($results !=FALSE && $query->rowCount() > 0) {
       if($results[0]['password'] == $password){
            $_SESSION['email'] = $email;
            return $query->fetchAll($q,0)==1 ? true:false;
        }
    }

    // return false by default
    return false;
}

顺便说一句,代码缩进是你的朋友;)

然而,这可以优化为更稳定:

function valid_credientials($email,$password){
    global $db;

    $q = "SELECT * FROM user WHERE email = :email AND password =:password";
    $query = $db->prepare($q);
    if(!$query) {
        throw new Exception('Failed to prepare the query');
    }

    $ret = $query->execute(array(":email" => $email, ":password" => $password));
    if(!$ret) {
        throw new Exception('Failed to execute the query');
    }

    $results = $query->fetchAll();
    if($results === FALSE) {
        throw new Exception('Failed to fetch results');
    }

    if(count($results) > 0) {
        // additional password check is not necessary
        return true;
    }

    // return false by default
    return false;
}
于 2013-04-13T13:06:07.983 回答
0

不知道你为什么写这么多代码

function valid_credientials($email,$password){
    global $db;

    $q = "SELECT 1 FROM user WHERE email = ? AND password = ?";
    $query = $db->prepare($q);
    $query->execute(func_get_args());
    return $query->fetchColumn();
}
于 2013-04-13T13:08:23.007 回答