0

我正在尝试创建一个注册表单来检查用户是否存在于数据库中,我插入了一个示例用户,当我尝试与该用户注册时,它并没有说它已经被使用。我做错了什么?

JavaScript:

function formSubmit()
    {
    document.getElementById('email_valid').innerHTML = '';

    var temail=document.forms["signup_form"]["temail"].value.replace(/^\s+|\s+$/g, '');


      var atpos=temail.indexOf("@");
        var dotpos=temail.lastIndexOf(".");
        if (atpos<1 || dotpos<atpos+2 || dotpos+2>=temail.length)
          {
          //alert("Not a valid e-mail address");
          setTimeout(function(){document.getElementById('email_valid').innerHTML = '<br/>Email must be valid...';},1000);
          var temailsub=0;
          }
          else
          {
          $.post('/resources/forms/signup/email.php',{email: temail}, function(data){
            document.getElementById('email_valid').innetHTML = data;
            if(data.exists){
                    document.getElementById('email_valid').innetHTML = '<br/>The email address you entered is already in use.';
                    var temailsub=0;
                }else{
                    var temailsub=1;
                }
            }, 'JSON');
          }
    if(temailsub==1e)
      {
        setTimeout(function(){document.getElementById("signup_form").submit();},1000);
      }
      else
      {

        return false;
      }
    }

PHP 文件(email.php):

<?php
header('content-type: text/json');
require_once $_SERVER['DOCUMENT_ROOT']."/resources/settings.php";
$query = $pdo->prepare("SELECT * FROM users WHERE email=:email");
$query->execute(array(
    ":email"=> $_POST['email']
));
echo json_encode(array('exists' => $query->rowCount() > 0));
?>

我已经检查并仔细检查了代码,我仍然看不出为什么它没有检测到电子邮件已被使用......我需要做些什么来解决这个问题并在未来避免这种情况?

4

1 回答 1

2

问题是PDOStatement::rowCount()返回受最后一条 SQL 语句影响的行数。您正在执行 a SELECT,因此该值将始终为0SELECT不影响任何行。相反,您需要计算行数:

$query = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email=:email");
$query->execute(array(
    ":email"=> $_POST['email']
));
$rows = $query->fetchColumn();

echo json_encode(array('exists' => $rows);

同样来自上面 jtheman 的评论,您应该在 JavaScript 中替换innetHTML为。innerHTML

于 2012-12-03T23:31:37.103 回答