user115422
user115422

Reputation: 4710

Check if user exists with AJAX and PHP

I am trying to create a signup form that checks if the user exists in the database, I inserted a sample user and when I tried signing up with that user it didn't say its already been taken. What have I done wrong?

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

The PHP file (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));
?>

I have checked and double checked the code, I still cannot see why its not detecting that the email has already been used... what do i need to do to fix this and avoid this in the future?

Upvotes: 0

Views: 1078

Answers (1)

Mike
Mike

Reputation: 24413

The problem is that PDOStatement::rowCount() returns the number of rows affected by the last SQL statement. You are performing a SELECT so this value will always be 0. SELECT does not affect any rows. Instead you need to count the number of rows:

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

Also from jtheman's comment above, you should replace innetHTML with innerHTML in your JavaScript.

Upvotes: 2

Related Questions