使用AJAX检查数据库中是否存在用户名

时间:2022-11-10 07:22:55

So basically, I want to add a feature to my registration form which I will check if that username already exists in the database.

基本上,我想在注册表单中添加一个功能,我将检查这个用户名是否已经存在于数据库中。

I have a few questions about AJAX -

我有几个关于AJAX的问题

1) I want to create an AJAX request on_change function, so something like this -

1)我想创建一个AJAX请求on_change函数,就像这样

$('#username').change(function() {
  $.ajax({
  url: "validation.php"
  });
});

So, as far as I understood, I must have all validations made in PHP inside the validation.php file, correct? Is there any special validation needed or can it be just simple validation with a sql statement - SELECT * FROM 'users' WHERE 'username' = '. $_POST['username'];

因此,据我所知,我必须在验证中使用PHP进行所有验证。php文件,对吗?是否需要任何特殊的验证,或者只是使用sql语句进行简单的验证——从'users' WHERE 'username' = '中选择*。$ _POST['用户名');

2) So as I understood I must pass the POST values via $.ajax too, correct? If yes, how will I be able to access them via the validation.php file?

2)如我所知,我必须通过$传递POST值。ajax,正确吗?如果是,我将如何通过验证访问它们。php文件吗?

3) After I get the results in validation.php file, how can I pass them back (true or false -- exists or doesn't exist)? I will need to pass them back, and then do an if check, if it's true - show an error that the username already exists, otherwise, don't show anything?

在我得到验证结果之后。php文件,如何将它们传回?我需要将它们传递回去,然后做一个if检查,如果它是真的-显示一个用户名已经存在的错误,否则,什么都不显示?

Hope, you understood what I'm about to create. I know there are a lot of tutorials over the internet, but I don't like to create something via tutorials, since if I create it by myself, it will be easier to understand next time ;)!

希望你明白我要创造什么。我知道网上有很多教程,但是我不喜欢用教程来创建,因为如果我自己创建,下次会更容易理解!

EDIT: In addition, I'm creating my website with CodeIgniter framework, so how would I pass the url attribute in ajax, to a CodeIgniter module?

编辑:另外,我正在用CodeIgniter框架创建我的网站,那么如何将ajax中的url属性传递给CodeIgniter模块?

4 个解决方案

#1


10  

Before continuing, SELECT * FROM 'users' WHERE 'username' = '. $_POST['username']; is just ASKING for a SQL Injection. I suggest you use PHP Data objects - http://php.net/manual/en/book.pdo.php.

在继续之前,从'users' WHERE 'username' = '中选择*。$ _POST['用户名');只是要求SQL注入。我建议您使用PHP数据对象——http://php.net/manual/en/book.pdo.php。

So as I understood I must pass the POST values via $.ajax too, correct? If yes, how I will be able to access them via validation.php file?

所以正如我所理解的,我必须通过$传递POST值。ajax,正确吗?如果是,我将如何通过验证访问它们。php文件吗?

Because this is a simple request, I suggest you use JQuery's method $.post(). Here's a sample based off of what you're trying to do.

因为这是一个简单的请求,所以我建议您使用JQuery方法$.post()。这是一个基于你要做的事情的例子。

$.post('validation.php',{username: $('#username').val()}, function(data){
    if(data.exists){
        //tell user that the username already exists
    }else{
        //username doesn't exist, do what you need to do
    }
 }, 'JSON');

jQuery's post method takes 4 parameters $.post(url, data, callback, datatype). In the example above, we will be posting the username with $('#username').val() to validation.php and expect a JSON response. When the request is finished, the callback function will be executed with data being the response from the request. Because we specified that that response will be JSON, we can access it just like a native object in javascript. Now let's move to validation.php

jQuery的post方法需要4个参数$。帖子(url、数据回调,数据类型)。在上面的示例中,我们将使用$('#username').val()将用户名发布到验证中。php和JSON响应。当请求完成时,回调函数将执行,数据是请求的响应。因为我们指定该响应是JSON,所以我们可以像javascript中的本机对象一样访问它。现在我们转到valid.php

Like I stated above, I suggested you use PDO for your database driver. So in this example, I will show you a basic usage of it.

如前所述,我建议您对数据库驱动程序使用PDO。在这个例子中,我将向你们展示它的基本用法。

//set the headers to be a json string
header('content-type: text/json');

//no need to continue if there is no value in the POST username
if(!isset($_POST['username']))
    exit;

//initialize our PDO class. You will need to replace your database credentials respectively
$db = new PDO('mysql:host=DATABASE_HOST;dbname=DATABASE_NAME','DATABASE_USERNAME','DATABASE_PASSWORD',array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

//prepare our query.
$query = $db->prepare('SELECT * FROM users WHERE username = :name');
//let PDO bind the username into the query, and prevent any SQL injection attempts.
$query->bindParam(':name', $_POST['username']);
//execute the query
$query->execute();

//return the json object containing the result of if the username exists or not. The $.post in our jquery will access it.
echo json_encode(array('exists' => $query->rowCount() > 0));

Now to recap, our jQuery script will post to validation.php where it selects a username from the database. It will return a JSON object that has a key of exists that is a boolean indicating if the username already exists as a row in your database. When the request is complete via jQuery, you can do what you need based off the result of the query. I hope this is a thorough explanation and leads you to what you are hoping to accomplish.

现在回顾一下,我们的jQuery脚本将发布到验证。从数据库中选择用户名的php。它将返回一个JSON对象,该对象具有一个存在的键,该键是一个布尔值,指示用户名是否已经作为数据库中的一行存在。当通过jQuery完成请求时,您可以根据查询的结果完成所需的工作。我希望这是一个完整的解释,并引导您实现您希望实现的目标。

#2


4  

With reading tutorials on the internet, you can learn lots of things. I recommend you to follow the instructions on the following page: http://blog.webwizo.com/2011/05/04/simple-login-with-php-and-jquery-ajax/

通过在网上阅读教程,你可以学到很多东西。我建议您遵循以下页面的说明:http://blog.webwizo.com/2011/05/04/simple-login- php-and-jquery-ajax/

You send the username via post to the specified php file, which searches for the username you have provided.

您将用户名通过post发送到指定的php文件,该文件搜索您提供的用户名。

Please, use the mysql_real_escape_string function on the input string, so hackers will not be able to use a sql injection attack on your website. It works like this:

请在输入字符串上使用mysql_real_escape_string函数,这样黑客就不会对您的网站进行sql注入攻击。是这样的:

$query = "SELECT * FROM users WHERE username = '".mysql_real_escape_string($_POST['username'])."'";
if (mysql_num_rows(mysql_query($query)) > 1)
{ 
    print "inuse";
} 

Then you can check the response value in your ajax jquery function. If the website returns the value "inuse", show an error message that the username is already in use. If not, the username is available.

然后可以在ajax jquery函数中检查响应值。如果该网站返回“inuse”值,则显示用户名已被使用的错误消息。如果不是,用户名是可用的。

But as I've said, please check the tutorial and the most important thing: Use mysql_real_escape_string to prevent sql injection attacks

但是正如我所说,请检查教程和最重要的事情:使用mysql_real_escape_string来防止sql注入攻击

#3


0  

Here is what I did on one of my website: on validation.php I count the number of member with the username then here is the jquery script:

以下是我在我的网站上做的:验证。我用用户名来计算成员的数量这是jquery脚本:

var username = $('#username').val();
$('#username').change(function() {
   $.ajax({
      url: "validation.php",
      type: 'POST',
      data: 'username=' + username,
      success: function(result){
                 if(result > 0){
                     // do something if username already exist
                 }
                 else{
                     // do something if username doesn't exist
                 }
               }
      });
});

#4


-2  

  1. if (mysql_num_rows(mysql_query("SELECT * FROM users WHERE username='".$_POST['username']."'")) < 1) { 
        true; 
    } else { 
        false; 
    }
    
  2. if (mysql_num_rows(mysql_query(“从用户名='”的用户中选择* .$_POST['username'].”)< 1){
  3. you can pass it by get or post methods. in validation.php you just have to write $somevar=$_POST['somevar'];

    您可以通过get或post方法传递它。在验证。你只需要写$somevar=$_POST['somevar'];

  4. as I just said you cant pass variables by post or get methods - to do this task, you must us GET.

    正如我刚才说过的,不能通过post或get方法传递变量——要完成这个任务,我们必须得到。

i hope i was helpful ;)

我希望我能帮上忙;

#1


10  

Before continuing, SELECT * FROM 'users' WHERE 'username' = '. $_POST['username']; is just ASKING for a SQL Injection. I suggest you use PHP Data objects - http://php.net/manual/en/book.pdo.php.

在继续之前,从'users' WHERE 'username' = '中选择*。$ _POST['用户名');只是要求SQL注入。我建议您使用PHP数据对象——http://php.net/manual/en/book.pdo.php。

So as I understood I must pass the POST values via $.ajax too, correct? If yes, how I will be able to access them via validation.php file?

所以正如我所理解的,我必须通过$传递POST值。ajax,正确吗?如果是,我将如何通过验证访问它们。php文件吗?

Because this is a simple request, I suggest you use JQuery's method $.post(). Here's a sample based off of what you're trying to do.

因为这是一个简单的请求,所以我建议您使用JQuery方法$.post()。这是一个基于你要做的事情的例子。

$.post('validation.php',{username: $('#username').val()}, function(data){
    if(data.exists){
        //tell user that the username already exists
    }else{
        //username doesn't exist, do what you need to do
    }
 }, 'JSON');

jQuery's post method takes 4 parameters $.post(url, data, callback, datatype). In the example above, we will be posting the username with $('#username').val() to validation.php and expect a JSON response. When the request is finished, the callback function will be executed with data being the response from the request. Because we specified that that response will be JSON, we can access it just like a native object in javascript. Now let's move to validation.php

jQuery的post方法需要4个参数$。帖子(url、数据回调,数据类型)。在上面的示例中,我们将使用$('#username').val()将用户名发布到验证中。php和JSON响应。当请求完成时,回调函数将执行,数据是请求的响应。因为我们指定该响应是JSON,所以我们可以像javascript中的本机对象一样访问它。现在我们转到valid.php

Like I stated above, I suggested you use PDO for your database driver. So in this example, I will show you a basic usage of it.

如前所述,我建议您对数据库驱动程序使用PDO。在这个例子中,我将向你们展示它的基本用法。

//set the headers to be a json string
header('content-type: text/json');

//no need to continue if there is no value in the POST username
if(!isset($_POST['username']))
    exit;

//initialize our PDO class. You will need to replace your database credentials respectively
$db = new PDO('mysql:host=DATABASE_HOST;dbname=DATABASE_NAME','DATABASE_USERNAME','DATABASE_PASSWORD',array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

//prepare our query.
$query = $db->prepare('SELECT * FROM users WHERE username = :name');
//let PDO bind the username into the query, and prevent any SQL injection attempts.
$query->bindParam(':name', $_POST['username']);
//execute the query
$query->execute();

//return the json object containing the result of if the username exists or not. The $.post in our jquery will access it.
echo json_encode(array('exists' => $query->rowCount() > 0));

Now to recap, our jQuery script will post to validation.php where it selects a username from the database. It will return a JSON object that has a key of exists that is a boolean indicating if the username already exists as a row in your database. When the request is complete via jQuery, you can do what you need based off the result of the query. I hope this is a thorough explanation and leads you to what you are hoping to accomplish.

现在回顾一下,我们的jQuery脚本将发布到验证。从数据库中选择用户名的php。它将返回一个JSON对象,该对象具有一个存在的键,该键是一个布尔值,指示用户名是否已经作为数据库中的一行存在。当通过jQuery完成请求时,您可以根据查询的结果完成所需的工作。我希望这是一个完整的解释,并引导您实现您希望实现的目标。

#2


4  

With reading tutorials on the internet, you can learn lots of things. I recommend you to follow the instructions on the following page: http://blog.webwizo.com/2011/05/04/simple-login-with-php-and-jquery-ajax/

通过在网上阅读教程,你可以学到很多东西。我建议您遵循以下页面的说明:http://blog.webwizo.com/2011/05/04/simple-login- php-and-jquery-ajax/

You send the username via post to the specified php file, which searches for the username you have provided.

您将用户名通过post发送到指定的php文件,该文件搜索您提供的用户名。

Please, use the mysql_real_escape_string function on the input string, so hackers will not be able to use a sql injection attack on your website. It works like this:

请在输入字符串上使用mysql_real_escape_string函数,这样黑客就不会对您的网站进行sql注入攻击。是这样的:

$query = "SELECT * FROM users WHERE username = '".mysql_real_escape_string($_POST['username'])."'";
if (mysql_num_rows(mysql_query($query)) > 1)
{ 
    print "inuse";
} 

Then you can check the response value in your ajax jquery function. If the website returns the value "inuse", show an error message that the username is already in use. If not, the username is available.

然后可以在ajax jquery函数中检查响应值。如果该网站返回“inuse”值,则显示用户名已被使用的错误消息。如果不是,用户名是可用的。

But as I've said, please check the tutorial and the most important thing: Use mysql_real_escape_string to prevent sql injection attacks

但是正如我所说,请检查教程和最重要的事情:使用mysql_real_escape_string来防止sql注入攻击

#3


0  

Here is what I did on one of my website: on validation.php I count the number of member with the username then here is the jquery script:

以下是我在我的网站上做的:验证。我用用户名来计算成员的数量这是jquery脚本:

var username = $('#username').val();
$('#username').change(function() {
   $.ajax({
      url: "validation.php",
      type: 'POST',
      data: 'username=' + username,
      success: function(result){
                 if(result > 0){
                     // do something if username already exist
                 }
                 else{
                     // do something if username doesn't exist
                 }
               }
      });
});

#4


-2  

  1. if (mysql_num_rows(mysql_query("SELECT * FROM users WHERE username='".$_POST['username']."'")) < 1) { 
        true; 
    } else { 
        false; 
    }
    
  2. if (mysql_num_rows(mysql_query(“从用户名='”的用户中选择* .$_POST['username'].”)< 1){
  3. you can pass it by get or post methods. in validation.php you just have to write $somevar=$_POST['somevar'];

    您可以通过get或post方法传递它。在验证。你只需要写$somevar=$_POST['somevar'];

  4. as I just said you cant pass variables by post or get methods - to do this task, you must us GET.

    正如我刚才说过的,不能通过post或get方法传递变量——要完成这个任务,我们必须得到。

i hope i was helpful ;)

我希望我能帮上忙;