检查用户是否存在于数据库(表单)中

时间:2010-09-12 16:27:12

标签: php javascript jquery mysql ajax

我有一个允许用户注册的脚本,它将数据导入MySQL表。

user_availability.php
http://pastebin.com/PSRndXbq

number.js
http://pastebin.com/iYAPuwN7

此脚本将告诉用户表中是否存在该编号。然而它不断地说它不在桌子上,尽管它在那里(通过PMA看)。

我尝试了一些东西,比如var_dump等来检查查询,它返回正常。我也尝试在if / else字符串中添加“no”,它也是一样的。考虑到这一点,似乎JS有错?

我的代码中是否有错误?

干杯

1 个答案:

答案 0 :(得分:1)

修改

JS:

$(document).ready(function()
{
    $("#number").blur(function()
    {
        $("#msgbox").removeClass().addClass('messagebox').text('Checking').fadeIn("slow");
        //check the username exists ajax
        // switch to ajax so we can handle errors...
        $.ajax({
            url: "user_availability.php",
            data: { user_name:$(this).val() },
            type: 'post',
            dataType: 'json',
            success: function(data) {
                if(!data.userExists) //if username not avaiable
                  {
                      $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
                    { 
                      $(this).html('<img src="img/off.png" alt="Number registered" />').addClass('messageboxerror').fadeTo(900,1);
                    });

                  }
                  else
                  {
                      $("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
                    { 
                      $(this).html('<img src="img/on.png" alt="Number unregistered"/>').addClass('messageboxok').fadeTo(900,1);    
                    });
                  }
            },
            error: function(request, status, exception){
                $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
                { 
                  $(this).html('<img src="img/off.png" alt="Number registered" />').addClass('messageboxerror').fadeTo(900,1);
                });
                // for debug in firefox/firebug only, if you open your js console you should see some error reporting
                try {
                    var data = $.parseJSON(request.responseText);
                    var error = (typeof data.error != 'undefned') ?  data.error : request.responseText;
                    console.log("Error: \"" + error +"\"");
                } catch (e) {
                    console.log("Couldn't parse as JSON: \""+request.responseText+"\"");
                }

            }
        });
});

PHP:

<?php
// config 
include("../config.php");

function return_error($error, $json = array()) {
   $json['error'] = $error;
   header('HTTP/1.0 500 Internal Server Error');
   header('Content-type: application/json'); // send json headers
   // dump the json value should look like {'userExists': true, 'error': 'Some MySQL Error text'}
   echo json_encode($json);
   exit;
} 

$json = array('userExists' => false);

if(!mysql_connect($host, $user, $pass) || !mysql_select_db($database))
{
    return_error(mysql_error(), $json);
}

// dont know your logic for checking with is_numeric so just apply that however, 
// i just changed the variable name so it matches up with what youre passing in the JS
$query = "SELECT email FROM recipients where email ='" . $_POST['user_name'] ."'";


$result = mysql_query($query);

if(!$result){
   return_error(mysql_error(), $json); 
}

$result = array('userExists' => false); // default to false

if(mysql_num_rows($result) > 0) {
  //username already exists
  $json['userExists'] = true; // we found a user so set to true
}

header('Content-type: application/json'); // send json headers
echo json_encode($json); // dump the json value should look like {'userExists': true}
exit;
?>

修改

好的,你可以使用变量名user_name

$.post("user_availability.php",{ user_name:$(this).val() } ,function(data){...});

然而在你的php中你正在使用$_POST['number']。除非我遗漏了某些内容,否则你需要在php中使用$_POST['user_name']或在js中使用{number: $(this).val()} ...他们应该使用相同的var名称。


'SELECT email FROM recipients where email =' . intval($_POST['number']);

此查询是否正确?不应该是更像下列之一:

'SELECT email FROM recipients where id =' . intval($_POST['number']);

OR

"SELECT id FROM recipients where email ='" . mysql_real_escape_string($_POST['email'])."'";

另外,为了便于阅读(可以帮助您避免拼写错误),您可能希望使用sprintf格式化查询字符串:

$query = sprintf(
  "SELECT id FROM recipients where email ='%s'", 
  mysql_real_escape_string($_POST['email'])
);