简体   繁体   English

通过php检查用户名是否存在-并保留值

[英]Check if username exists by php - and keep values

I'm trying to write a registration form, and when the user press the "submit" button, I want to check if the username already exists - and if so, to show a pop-up window that says "user name already exists - please change it". 我正在尝试编写注册表格,当用户按下“提交”按钮时,我要检查用户名是否已经存在-如果存在,则显示一个弹出窗口,显示“用户名已经存在-请更改”。 when the user closes that pop-up window using Javascript - I want the rest of the fields that the user inserts to stay in their place (I mean, only the username will be deleted - but the first name for example, will stay) 当用户使用Javascript关闭该弹出窗口时-我希望用户插入的其余字段保留在原处(我的意思是,只会删除用户名-但例如保留名字)

here's the code I wrote: 这是我写的代码:

$con=mysqli_connect("localhost","root","","shnitzale");
        // Check connection
        if (mysqli_connect_errno())
          {
          echo "Failed to connect to MySQL: " . mysqli_connect_error();
          }

         $check="SELECT count (username) as num FROM registered_clients WHERE username=$_GET[User]";
         if (!mysqli_query($con, $check))
         {
             echo "Username already exist";
         }
         else
         {
             $sql="INSERT INTO registered_clients (Username, Password, First_name, Last_name,
                Day, Month, Year, Gender, Address, City, Phone_Number1, Phone_number2, Email)
                VALUES
                ('$_GET[User]','$_GET[Password]','$_GET[Fname]','$_GET[Lname]','$_GET[Day]',"
                     . "'$_GET[Month]','$_GET[Year]','$_GET[gender]','$_GET[Address]','$_GET[City]',"
                     . "'$_GET[Phone1]','$_GET[Phone2]','$_GET[Email]')";

             if (!mysqli_query($con,$sql))
             {
               die('Error: ' . mysqli_error($con));
             }

             echo "Thank you $_GET[Fname] $_GET[Lname]";
         }
            mysqli_close($con);

all of this is in a seperate php file that I go to after I press the "submit" button, I understand that I need to check the username validation before I get to this page, but I don't really know how... Thank you! 所有这些都在我单击“提交”按钮后进入的单独的php文件中,我了解到进入此页面之前我需要检查用户名验证,但是我真的不知道如何...谢谢!

Your current username check isn't working due to this: 由于以下原因,您当前的用户名检查不起作用:

if (!mysqli_query($con, $check))
{
    echo "Username already exist";
}

This will never occur. 这将永远不会发生。 Your current query will always return a valid result, even if no usernames are found. 即使未找到用户名,您当前的查询也将始终返回有效结果。 num will simply be 0. num只会是0。

Here's one way to do it: 这是一种实现方法:

$username = mysqli_real_escape_string($con, $_GET['User']); // Do some minimal sanitization at least!
$check = "SELECT username FROM registered_clients WHERE username='$username'";
$result = mysqli_query($con, $check);
if(mysqli_num_rows($result)) {
    echo "Username already exists";
}

This way you are pulling the actual usernames found, and counting them. 这样,您就可以提取找到的实际用户名并进行计数。 Alternatively you could still use your count (username) as num query, but then you'd have to fetch the results of the query and look at the value of num . 另外,您仍然可以将您的count (username) as num查询,但是随后您必须获取查询结果并查看num的值。

Note that your INSERT query is still wide open to SQL injection. 请注意,您的INSERT查询仍然可以进行SQL注入。 You need to sanitize all of those $_GET parameters before using them in your query. 您需要先清理所有这些$_GET参数,然后才能在查询中使用它们。

You either need AJAX http://www.w3schools.com/ajax/ and check, if the username is available without loading another page or you can set the register form's action to the register page and insert all valid form data again. 您或者需要AJAX http://www.w3schools.com/ajax/并检查用户名是否可用而无需加载其他页面,或者您可以将注册表单的操作设置为注册页面并再次插入所有有效的表单数据。

Don't forget to sanitize your user data before! 不要忘了先清理用户数据!

If you want to do this with ajax: Create a seperate page (for now ill call it) usernamecheck.php 如果要使用Ajax进行此操作,请执行以下操作:创建一个单独的页面(现在生病了),请输入usernamecheck.php

/*
    $database_connection = database connection and stuff
    Also, does your table have a primary key 'id'? I'd highly recommend it.
*/

$username = mysqli_real_escape_string($database_connection, $_GET['username']; // Use $_GET or $_POST depending on the AJAX request.
if (strlen($username) > 3){ // Only check if the username string is bigger than 4 characters. No point in checking an empty username.
    $UserCheck = mysqli_query("SELECT id FROM registered_clients WHERE username = '$username' LIMIT 1");
    if (mysqli_num_rows($UserCheck) > 0){
        die('<p style="color: red;">The username '.$username.' is already taken.</p>');
    } else {
        die('<p style="color: green;">The username '.$username.' is available.</p>');
    }
}

If you target your AJAX request to usernamecheck.php?username=superman and display the output of the page directly under the username field, the user would get a live update from the server. 如果将AJAX请求定向到usernamecheck.php?username = superman并在用户名字段的正下方显示页面的输出,则用户将从服务器获得实时更新。

You can also change the output of the script to a 1 or 0, so that you can pick it up in javascript. 您还可以将脚本的输出更改为1或0,以便可以在javascript中进行拾取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM