2

I'm creating some client side validation for my email field. Checking if the email already exists in the database. However the result always says that the email address is available whether it already exists or not.

here's my JS

$(document).ready(function() {
    $("#email_address").blur(function() {
        var email = $("#email_address").val();
        $("#emailError").html('<img alt="" src="img/loading.gif"/>');
            $.post("check_username_new.php", {email:email},
            function(result) {
                if (result > 0) {
                    $("#emailError").html("Not Available");
                    console.log(result);
                }
                else {
                    $("#emailError").html("Available");
                    console.log(result);
                    }
                });
    });
});

PHP

<?php
  require('includes/application_top.php');

$email = mysql_real_escape_string(strtolower($_POST["email_address"]));
$sql = "SELECT count(*) FROM customers WHERE customers_email_address = '" . $email . "'";
$result = mysql_query($sql) or die("Error: " . mysql_error());

if(mysql_num_rows($result) > 0) {
    echo 1;
}
else {
    echo 0;
}

?>

As far as I can tell, my jQuery is working, and seems to be an issue with the php. I am not getting any errors to work from either, so naturally I am a bit stuck.

Hopeless
  • 375
  • 1
  • 4
  • 17
  • I'm sure there's more to it than this, but I would update the PHP script to use $_GET['email_address'] and test it yourself in a browser. Do you get a blank screen still? – CT14.IT Jul 17 '15 at 08:39

2 Answers2

2

You are using COUNT which will return 0 if not data found and the number of records found. In both of the cases there will be a row in the resource. So mysql_num_rows will always be 1.

You should do -

$result = mysql_query($sql) or die("Error: " . mysql_error());
$data = mysql_fetch_assoc($result); // You can use any fetch method
if($data['count(*)'] > 0) {
    echo 1;
}
else {
    echo 0;
}

mysql is deprecated. Prefer using PDO or mysqli

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
  • I tried this method, and yes before I noticed that my query was always returning 1. Now this returns as 0. However I am still getting the same issue. – Hopeless Jul 17 '15 at 09:24
  • My bad. Check the updated answer. use `assoc` instead of `object`. – Sougata Bose Jul 17 '15 at 09:25
  • The result is now the opposite, every value entered now returns as not available, could this be an issue with my php not reading the database properly? – Hopeless Jul 17 '15 at 10:37
0

I suspect that you should do

count(*)

or

mysql_num_rows()

not both.

count is probably better, see SELECT COUNT() vs mysql_num_rows();

Community
  • 1
  • 1
rhorvath
  • 3,525
  • 2
  • 23
  • 30