I am trying to check if an input value already exists in my database.
So far I got the following but this always returns me "Invalid" (even if I enter a matching value) so my guess is I have an error in the part after my SELECT query or in my If Else logic.
Can someone tell me how to do this right?
My JS:
$('#btnCheck').click(function() {
var username = $('#username').val();
$.ajax({
url: 'userSubmit.php',
type: 'POST',
data: {username: username},
success: function(response){
if(response == 'valid') {
alert('Valid');
} else {
alert('Invalid');
}
}
});
});
My PHP:
$username = $_POST['username'];
$conn = new mysqli($host, $username, $password, $database);
if($conn->connect_error) {
die("Connection Error: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT username FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
if($stmt->num_rows > 0) {
echo "valid";
} else {
echo "invalid";
}