所以我试图检查该电子邮件是否已在使用(用于重置密码)。所以我有我的 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
。有任何想法吗?这可能是我的代码中的错误吗?
最佳答案
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']);
因为有时输入字段中会有额外的空格。
关于javascript - PHP AJAX 总是返回相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25493492/