Reputation: 395
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.
Upvotes: 2
Views: 113
Reputation: 31739
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
Upvotes: 2
Reputation: 3725
I suspect that you should do
count(*)
or
mysql_num_rows()
not both.
count is probably better, see SELECT COUNT() vs mysql_num_rows();
Upvotes: 0