-3

我正在为登录页面创建一个有效的凭证功能。
如果我使用以下代码在函数外部使用该函数,则该函数有效:

if(isset($_POST['email'])){
    $email = $_POST['email'];
    $password = $_POST['password'];

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

    if($results !=FALSE && $query->rowCount() > 0) {
    if($results[0]['password'] == $password){
    $_SESSION['email'] = $email;
}

但是,如果我从外部函数调用该函数,则不会发生任何事情,就好像登录凭据有问题一样。

功能:

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

    $email = $_POST['email'];
    $password = $_POST['password'];
    $q = "SELECT * FROM user WHERE email = :email";
    $query = $db->prepare($q);
    $query->execute(array(":email" => $email));
    $results = $query->fetchAll();
    if($results !=FALSE && $query->rowCount() > 0) {
    if($results[0]['password'] == $password){
    $_SESSION['email'] = $email;

}}

}

isset帖子:

 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();

        }
    }

我正在考虑连接问题,但如果我使用此功能,它会返回电子邮件。

function valid_credientials($email,$password){
    $test = $db->query("SELECT `email` FROM `user`");
    while($row = $test->fetch(PDO::FETCH_ASSOC)){ 
        echo $row['email'], '<br>';
    } 
}
4

2 回答 2

1

看你的代码,

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

    $email = $_POST['email'];
    $password = $_POST['password'];
    $q = "SELECT * FROM user WHERE email = :email";
    $query = $db->prepare($q);
    $query->execute(array(":email" => $email));
    $results = $query->fetchAll();
    if($results !=FALSE && $query->rowCount() > 0) {
    if($results[0]['password'] == $password){
       $_SESSION['email'] = $email;

    }
}

您从 $_POST 获取值,您根本不需要这两行,因为您的函数参数中有电子邮件和密码。

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

您还检查了函数的返回值,但您的函数没有返回任何内容。通过下面的代码,它根据条件返回真或假。

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

    $email = $_POST['email'];
    $password = $_POST['password'];
    $q = "SELECT * FROM user WHERE email = :email";
    $query = $db->prepare($q);
    $query->execute(array(":email" => $email));
    $results = $query->fetchAll();
    if($results !=FALSE && $query->rowCount() > 0) {
    if($results[0]['password'] == $password){
       $_SESSION['email'] = $email;
       return true;
    }
    return false;
}
于 2013-04-13T05:44:01.627 回答
0

您的valid_credentials函数不返回值。

下面的 if 语句,将返回 NULL(这不是肯定的,只是猜测),它不等于 false,因此在下一个 if 语句期间错误数组仍然是空的

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

}
于 2013-04-13T05:35:07.487 回答