我之前提出了类似的问题,但我认为我现在更接近答案了。
我有一个功能可以验证用户的电子邮件地址和密码,然后才能登录个人资料。
如果电子邮件不正确,则会生成错误消息;它回应“找不到匹配的电子邮件”。
当我输入正确的电子邮件和密码时,不会返回任何内容。但如果我输入错误的密码和错误的电子邮件,它会给我“找不到匹配的电子邮件”。正确的电子邮件但密码错误也会发生同样的事情。
我尝试使用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;
}
帖子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();
}
}
答案 0 :(得分: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;
}
答案 1 :(得分:0)
Dunno为什么要写这么多代码
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();
}