检查用户名是否可用于AJAX

时间:2010-08-03 02:06:33

标签: php javascript ajax

我正在使用AJAX的基本注册表单,但表单未连接到数据库。我显然忽视了一些事情。

所以这是我要验证的字段。

Username:<input type="text" name="user" id="user" maxlength="30">
<span id="msgbox" style="display:none"/></input>

然后我使用jQuery,这是代码:

$(document).ready(function() {
    $("#user").blur(function() {

        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
        //check the username exists or not from ajax
        $.post("user_availability.php",{ user_name:$(this).val() },
            function(data) {
                if(data=='no') { //if username not avaiable
                    $("#msgbox").fadeTo(200,0.1,function() {//start fading the messagebox
                        //add message and change the class of the box and start fading
                        $(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
                    });       

                } else {
                    $("#msgbox").fadeTo(200,0.1,function() { //start fading the messagebox
                        //add message and change the class of the box and start fading
                        $(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);   
                    });
                } // else
             } // function

        ); // $.post
    }); // blur
}); // ready

我有这段代码,user_availability.php

mysql_connect(localhost,$user,$password);
    or die('There is error to connect to server:-'.mysqli_connect_error());

$db_selected = mysql_select_db($database);
$user_name=$_POST['user_name'];
$sql = "select * from members where username='$user_name'";
$result = mysql_query($sql);

while($row = mysql_fetch_assoc($result))   
{
    $existing_users[] = $row['username'];
}

if (in_array($user_name, $existing_users))
{
    echo "no"; //user name is not availble
}
else
{
    echo "yes"; //user name is available
}

我没有数据库错误。表格将更加丰富,但我不能让它与这个领域合作。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

在select语句中只是一个挑剔。由于您只需要输入输入用户名的行数,因此您无需执行“select *”,因为根据您的users表中的列数,您可能会返回相当多的数据。我会修改你的查询是这样的:

$sql = "select COUNT(username) from members where username=$user_name";

然后检查以确保查询结果等于零。如果是,则用户名可用。

我知道以上不是你问题的答案,但只是想我会指出它,因为这看起来是一个很大的功能,取决于你的注册表格上的流量和创造力你的访客。

答案 1 :(得分:-1)

检查您的查询:

 $sql = "select * from members where username='$user_name'";

我这个上面的查询应该是:

 $sql = "select * from members where username=$user_name";
相关问题