PDO fetch vs rowcount

时间:2017-08-31 15:35:16

标签: php mysql pdo

我正在使用PDO在PHP中创建登录脚本,但遇到了一些小问题。我已经检查了数据是否在字段中,但不确定如何检查用户名和密码组合是否正确。这是检查用户名和密码的片段:

list2env(lst, envir = .GlobalEnv)

当我输入用户名和密码的任意组合时,我得到输出为假(即echo'no')。有人可以帮我一把吗?

更新:修改了片段

我使用过password_verify,但我仍然有相同的结果:

# if data is valid, check against values held in the database
if ($valid) {
    $sql = 'SELECT COUNT(*) FROM authors
    WHERE email = :email AND password = :password';

    $s = $dbConnection->prepare($sql);
    $s->bindValue(':email', $email);
    $s->bindValue(':password', $password);
    $s->execute();

    $row = $s->fetch();

    if($row==1){
        echo "ok";
    }else{
        echo "no";
    }
}

var_dump错误数据:

// if data is valid, check against values held in the database
if ($valid) {
    $sql = 'SELECT * FROM author
    WHERE email = :email';

    $s = $dbConnection->prepare($sql);
    $s->bindValue(':email', $email);
    $s->execute();

    $row = $s->fetch();
    var_dump($row);

    if(count($row) > 0 && password_verify($password, $row['password'])){
        echo 'ok';
        exit;
    }else {
        echo 'Username and Password are not found';
    }
}

正确数据的var_dump:

bool(false) Username and Password are not found

1 个答案:

答案 0 :(得分:0)

让它排序。我使用的解决方案是:

# if data is valid, check against values held in the database and then action as appropriate
if ($valid) {
    $sql = 'SELECT id, email, password FROM author
    WHERE email = :email AND password = :password';

    $s = $dbConnection->prepare($sql);
    $s->bindValue(':email', $email);
    $s->bindValue(':password', $password);
    $s->execute();

    $data = $s->fetch();
    if($data != NULL){
        $_SESSION['loggedIn'] = TRUE;
        $_SESSION['email'] = $email;
        $_SESSION['id'] = $data['id'];
        header('Location:../admin/');
        exit;
    }else{
        unset($_SESSION['loggedIn']);
        unset($_SESSION['email']);
        unset($_SESSION['id']);
        echo 'Incorrect username/password combination';
    }
}