I am trying to get my form for checking if a username exist in mysql database. It looks like the javascript is working. I have added username "tester" in my database, but I still get a message that the username is available, when I try to add that name. My db connection is working fine on my other pages
Can anybody see what is wrong?
dbconfic.inc.php
<?php
$db_host = "localhost";
$db_user = "root";
$db_pass = "root";
$db_name = "test";
// connection:
$mysqli = new mysqli($db_host, $db_user, $db_pass , $db_name);
// tjek conenction:
if (mysqli_connect_errno()) {
printf("Connect failed: %s
", mysqli_connect_error());
}
// vi kører utf-8 på connection:
$mysqli->set_charset("utf-8");
?>
index.php
<script type="text/javascript">
$(document).ready(function(){
$('#username').keyup(function() {
var usercheck = $(this).val();
$('#usercheck').html('<img src="loading.gif" width="150" />');
$.post("check.php", {user_name: usercheck} , function(data)
{
if (data.status == true)
{
$('#usercheck').parent('div').removeClass('has-error').addClass('has-success');
} else {
$('#usercheck').parent('div').removeClass('has-success').addClass('has-error');
}
$('#usercheck').html(data.msg);
},'json');
});
});
</script>
</head>
<body>
<form>
<div class="form-group">
<label for="exampleInputEmail1">User Name</label>
<input type="text" class="form-control" name="username" id="username" placeholder="user Name">
<span id="usercheck" class="help-block"></span>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
check:
<?php
include 'dbconfic.inc.php';
if(isset($_POST['user_name']) && $_POST['user_name'] != '')
{
$response = array();
$username = mysqli_real_escape_string($mysqli,$_POST['user_name']);
$sql = "SELECT username FROM login WHERE users.username='".$username."'";
$res = mysqli_query($mysqli, $sql);
$count = mysqli_num_rows($res);
if($count > 0)
{
$response['status'] = false;
$response['msg'] = 'Username already exists.';
}
else if(strlen($username) < 6 || strlen($username) > 15){
$response['status'] = false;
$response['msg'] = 'Username must be 6 to 15 characters';
}
else if (!preg_match("/^[a-zA-Z1-9]+$/", $username))
{
$response['status'] = false;
$response['msg'] = 'Use alphanumeric characters only.';
}
else
{
$response['status'] = true;
$response['msg'] = 'Username is available.';
}
echo json_encode($response);
}?>