douche3244 2014-08-25 20:02
浏览 21
已采纳

PHP AJAX总是返回相同的结果

So I'm trying to check if the email is already in use (for a password reset). So I have my 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");
            }
        });
});
});

And then my 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;
}

So I start off by making sure there's a recording in my DB. Which there is, so I enter it. Now I go over to the console and all I get is Bad, which means that the email is not found, but it's in the database. So I'd assume all it returns is 0. Any ideas? Could it be an error in my code?

  • 写回答

1条回答 默认 最新

  • duanmao9918 2014-08-25 20:15
    关注

    The PDO documentation warns that rowCount might not work with all drivers. A more reliable and efficient way to do it is:

    $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;
    }
    

    Another thing to try:

    $email = trim($_POST['email']);
    

    because sometimes there's extra whitespace in theinput field.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题