所以我正在尝试检查电子邮件是否已被使用(用于密码重置)。所以我有我的JS
//Check if email exists
$(document).ready(function() {
//listens for typing on the desired field
$("#email").keyup(function() {
//gets the value of the field
var email = $("#email").val();
//here is where you send the desired data to the PHP file using ajax
$.post("../classes/check.php", {email:email},
function(result) {
if(result == 1) {
//Email available
console.log("Good");
}
else {
//the email is not available
console.log("Bad");
}
});
});
});
然后我的PHP
<?php
//Include DB
include_once '../db.php';
if(isset($_POST['email'])){
//Get data
$email = htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8');
}
else{
header('Location: /');
}
//Send requst to DB
$stmt = $con->prepare("SELECT * FROM users WHERE email = :email");
$stmt->bindValue(':email', $email, PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount() > 0){
//Email found
echo 1;
}
else{
//Email not found
echo 0;
}
所以我首先要确保我的数据库中有录音。哪有,所以我输入它。现在我转到控制台,我得到的只是Bad
,这意味着电子邮件不,但它在数据库中。所以我假设它返回的是0
。有任何想法吗?这可能是我的代码中的错误吗?
答案 0 :(得分:1)
PDO文档警告rowCount
可能不适用于所有驱动程序。一种更可靠,更有效的方法是:
$stmt = $con->prepare("SELECT COUNT(*) as count FROM users WHERE email = :email");
$stmt->bindValue(':email', $email, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row['count'] > 0) {
echo 1;
} else {
echo 0;
}
要尝试的另一件事:
$email = trim($_POST['email']);
因为有时在输入字段中会有额外的空格。