没有与数据库的连接

时间:2013-11-23 22:12:04

标签: php ajax database

我在运行以下脚本时遇到问题。它运行正常,但AJAX部分除外。它不会调用url“check_username.php”。我检查了数据库连接。

任何帮助都将受到高度赞赏。 感谢

jquery代码 -

<script type="text/javascript">


$(document).ready(function() {


        //the min chars for username
        var min_chars = 3;

        //result texts
        var characters_error = 'Minimum amount of chars is 3';
        var checking_html = '<img src="images/loading.gif" /> Checking...';

        //when button is clicked
        $('#check_username_availability').click(function(){
            //run the character number check
            if($('#username').val().length < min_chars){
            //if it's bellow the minimum show characters_error text
            $('#username_availability_result').html(characters_error);
        }else{          
            //else show the cheking_text and run the function to check
            $('#username_availability_result').html(checking_html);
            check_availability();
        }
    });


});

//function to check username availability   
function check_availability(){  

    //get the username
    var username = $('#username').val();

    //use ajax to run the check

     $.post("check_username.php", { username: username },   //This part is not being executed . 
        function(result){
            //if the result is 1
            if(result == 1){
                //show that the username is available
                $('#username_availability_result').html('<span class="is_available"><b>' +username + '</b> is Available</span>');
            }else{
                //show that the username is NOT available
                $('#username_availability_result').html('<span     class="is_not_available"><b>' +username + '</b> is not Available</span>');
                }
        });

}  
</script>`

check_username.php -

<?php


mysql_connect('localhost', 'root', '');
mysql_select_db('modal');


$username = mysql_real_escape_string($_POST['username']);


$result = mysql_query("SELECT username FROM users WHERE username=`$username`");
$num_rows = mysql_num_rows($result);


//if number of rows fields is bigger them 0 that means it's NOT available '
if($numrows>0) {
echo 0;

}else{

    echo 1;
}

?>

1 个答案:

答案 0 :(得分:0)

您的查询会返回users中的所有行,因为您未指定任何特定行。因此$result将保留检索到的第一行(并且您无法确定这是哪一行)。您基本上检查用户名的随机行。如果你想遍历所有行,你可以用while ($result = mysql_fetch_array(mysql_query(..)))执行此操作,但我建议使用SQL。

$result = mysql_query("SELECT username FROM users WHERE username=`$username`");
$num_rows = mysql_num_rows($result);
echo $num_rows;
  • 查询

    SELECT username FROM users WHERE username=`$username`
    

    现在将username==$username所有行。所以你会得到0或1行(总而言之,而不是之前的#of_users)。

  • mysql_num_rows将计算返回的行数(0或1),因此您可以直接打印它。

另请注意,mysql_*函数为officially deprecated,因此不应在新代码中使用。您可以使用PDO或MySQLi。有关详细信息,请参阅this answer on SO