2010-08-03 39 views
1

我正在使用帶有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 
} 

我沒有得到任何數據庫錯誤。表格將會更加豐富,但我無法使用它來與這個領域合作。有什麼建議麼?

+0

我會從分開解決php頁面本身開始。添加一些代碼來處理$ _GET變量,然後檢查以查看:當它直接訪問它時是否提供了預期的響應? – 2010-08-03 02:22:38

+0

另外,使用Firebug(或類似的工具來檢查請求參數)來驗證你的javascript函數是否將正確的參數傳遞給了php頁面。 – 2010-08-03 02:25:59

+0

嗯...不。問題是這樣的。它沒有連接到數據庫。 我的意思是,當一個新用戶輸入他的用戶名,並且它已經在數據庫中。它仍然說'用戶名可用'..但事實是它不可用。 – mayumi 2010-08-03 02:27:31

回答

1

就在雞蛋裏挑骨頭的select語句。由於您只需要知道輸入的用戶名有多少行,因此根據用戶表中的列數,您不需要執行「select *」操作即可返回相當多的數據。我會修改您的查詢,如下所示:

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

然後您檢查以確保查詢的結果等於零。如果確實如此,則用戶名可用。

我知道上述不是你的問題的答案,但只是想我會指出,因爲這看起來是一個函數,將被調用很多,取決於你的註冊表格上的流量和您的訪客的創意。

-1

檢查查詢:

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

我這上面的查詢應該是:

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

不,用戶名是一個字符串而不是數字(我會假設)所以OP肯定需要引號 – SmokeyPHP 2013-08-12 14:19:07

+0

引用或無引號,它仍然是一個很糟糕的方式來做到這一點很容易SQL注入 – Izkata 2013-08-12 14:20:42