我正在使用Jquery验证库来验证我的注册表单。一切正常但我正在尝试使用AJAX来查看数据库中是否存在用户名。 ajax请求有效,但似乎总是评估为true,它告诉我用户名已被占用。我找不到关于远程功能的很多文档,所以我被卡住了。我的代码如下。
<input type ='text'placeholder='Username' name="username" id="username" >
Jquery文件
$("#listener-register").validate({
rules: {
username: {
required: true,
remote: "http://... /check_username.php"
}, ....
PHP文件
if(isset($_POST["username"]))
{
$con = new mysqli(...);
//received username value from registration page
$username = $mysqli->real_escape_string ($_POST["username"]);
//check username in db
$results = mysqli_query($con,"SELECT * FROM ... WHERE username='$username'");
$username_exist = mysqli_num_rows($results); //records count
//if returned value is more than 0, username is not available
if($username_exist) {
die('Username Not Available, Please Choose Another!');
}else{
die('Username Is Available');
}
}
提前感谢您的帮助!!
答案 0 :(得分:0)
mysqli_num_rows以这种方式返回0或更多,它将始终返回
if($username_exist == 1) {
die('Username Not Available, Please Choose Another!');
}else{
die('Username Is Available');
}
答案 1 :(得分:0)
if($username_exist > 0) { //denotes there is a similar username already present in the database
die('Username Not Available, Please Choose Another!');
}else{
die('Username Is Available');
}
}
我们不比较($username_exists == 1)
的原因是因为如果存在多个匹配的用户名,这种情况将会失败(尽管这种情况不太可能出现,但即便如此也是如此。)因此检查是否大于0