I'm running into a problem where the code keeps on showing that the user name is available, even though it is existing in the DB. Can anyone solve the problem that I'm running into? Down below is my code.
PHP
// Define $username
$username=$_POST["emailAddress"];
// Create Connection
$db = new mysqli($server, $user, $password, $database);
// Check Connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
// SQL query to fetch registerd users and finds user match.
$query = "SELECT email_address FROM users WHERE email_address='$username'";
$result = mysqli_query($db,$query);
$rows = mysqli_num_rows($result);
//if number of rows fields is bigger them 0 that means it's NOT available '
if($rows>0){
//and we send 0 to the ajax request
echo 0;
}else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
mysqli_close($db); // Closing Connection
jQuery
$(document).ready(function () {
//when button is clicked
$('[name="checkAvail"]').on("click", function () {
check_availability();
});
});
//function to check username availability
function check_availability() {
//get the username
var username = $('[name="emailAddress"]').val();
//use ajax to run the check
$.post("checkusers.php",
function (result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('.existingUser').html(username + ' is Available');
} else {
//show that the username is NOT available
$('.existingUser').html(username + ' is NOT Available');
}
});
}
HTML
<div class="form-group">
<button class="btn btn-default" name="checkAvail">Check Availability</button>
<label for="emailAddress" class="col-sm-5 control-label">Email:</label>
<div class="col-sm-4">
<input type="email" class="form-control" id="emailAddress" name="emailAddress" placeholder="Email" autocomplete="off">
</div>
</div>