检查是否正在使用用户名

时间:2016-03-06 09:38:29

标签: php mysql login

我想知道是否以及如何检查是否正在使用用户名。

我听说你可以用 jQuery 做到这一点,但我只想要一些简单的东西,因为我是初学者。

我已经尝试过了,但我无法接缝以使其正确。我只是将它连接到一个mysql数据库但是因为当一个用户名与另一个帐户的密码相同时尝试登录时,这是一个问题,所以我需要这个来阻止人们添加多个用户名。

这是我的注册表单和php的简单代码

<form action="" method="POST">
    
    <p><label>name&nbsp;&nbsp; : </label>
	 <input id="password" type="text" name="name" placeholder="name" /></p>
	 
    <p><label>User Name : </label>
	<input id="username" type="text" name="username" placeholder="username" /></p>
	
	<p><label>E-Mail&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; : </label>
	 <input id="password" type="email" name="email"/></p>
 
     <p><label>Password&nbsp;&nbsp; : </label>
	 <input id="password" type="password" name="password" placeholder="password" /></p>
 
  
 
    <a class="btn" href="login.php">Login</a>
    <input class="btn register" type="submit" name="submit" value="Register" />
    </form>
</div>
<?php

	require('connect.php');
    // If the values are posted, insert them into the database.
    if (isset($_POST['username']) && isset($_POST['password'])){
        $username = $_POST['username'];
		$email = $_POST['email'];
        $password = $_POST['password'];
        $name = $_POST['name'];
 
        $query = "INSERT INTO `user` (username, password, email, name) VALUES ('$username', '$password', '$email', '$name')";
        $result = mysql_query($query);
        if($result){
      
        }
    }

?>

4 个答案:

答案 0 :(得分:0)

对于初学者而言,你不想仅依靠类似于唯一字段的内容来执行此操作,当然,您需要将该属性添加到数据库中的用户名列,但在上面您想要某种类型的在它之上的正面保护而不依赖于你的数据库在INSERT INTO上抛出错误,你也想要使用mysqli来解决所有这一问题,而不是旧版本的mysql。它很容易受到剥削而不再是普通的做法,这里的每个文件都应该是这样的:

  

connect.php

<?php
$conn = mysqli_connect("localhost","username","password","database");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>
  

register.php

<form action="insertuser.php" method="POST">
    Username:
    <input type="text" name="username" placeholder="Username" />  
    <br />
    Password:
    <input type="password" name="password" placeholder="Password" />
    <br />
    Name:
    <input type="text" name="name" placeholder="Name" />  
    <br />
    Email address:
    <input type="text" name="email" placeholder="Email address" />
    <br /><br />
    <input type="submit" value="Register" />  
</form>
<?php 
// If there's an error
if (isset($_GET['error'])) {
    $error = $_GET['error'];
    if ($error == "usernametaken") {
        echo "<h4>That username is taken!</h4>";
    } elseif ($error == "inserterror") {
        echo "<h4>Some kind of error occured with the insert!</h4>";
    } else {
        echo "<h4>An error occured!</h4>";
    }
    echo "<br />";
}
 ?>
Already have an account? <a href="login.php">Login here</a>
  

insertuser.php

<?php       
    // Stop header errors
    ob_start();
    // Check if form has been posted
    if (isset($_POST['username'])){
        // Requre database connection file
        require('connect.php');
        // Clean the variables preventing SQL Injection attack
        $username = mysqli_real_escape_string($conn, $_POST['username']);
        $email = mysqli_real_escape_string($conn, $_POST['email']);
        $password = mysqli_real_escape_string($conn, $_POST['password']);
        $name = mysqli_real_escape_string($conn, $_POST['name']);
        // Check if the username exists
        // Construct SELECT query to do this
        $sql = "SELECT id FROM user WHERE username = '".$username."';";
        $result = mysqli_query($conn, $sql);
        $rowsreturned = mysqli_num_rows($result);
        // If the username already exists
        if ($rowsreturned != 0) {
            echo "Username exists, redirecting to register.php with an error GET variable!";
            // Redirect user
            header('Location: register.php?error=usernametaken');
        } else {
            // Construct the INSERT INTO query
            $sql = "INSERT INTO user (username, password, email, name) VALUES ('".$username."', '".$password."', '".$email."', '".$username."');";
            $result = mysqli_query($conn, $sql);
            if($result){
                // User was inserted
                echo "User inserted!";
                /* DO WHATEVER YOU WANT TO DO HERE */
            } else {
                // There was an error inserting
                echo "Error inserting, redirecting to register.php with an error GET variable!";
                // Redirect user
                header('Location: register.php?error=inserterror');
            }
        }
    }
?>

祝你工作顺利,我希望这会有所帮助!

詹姆斯

答案 1 :(得分:0)

if (isset($_POST['username']) && isset($_POST['password'])){
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $name = $_POST['name'];

    $query = "select username from user where username = '$username'";
    $res = mysql_query($query);
    $rows = mysqli_num_rows($res);
    if ($rows > 0) {
        print 'Username already exists...';
    } else {
        $query = "INSERT INTO `user` (username, password, email, name) VALUES ('$username', '$password', '$email', '$name')";
        $result = mysql_query($query);
        if($result){

        }
    }

}

答案 2 :(得分:0)

这是另一个例子:),成功。

<?php

    //Set empty variables.
    $usernameError = $emailError = $passwordError = $nameError = $okmsg = "";
    $username = $password = $email = $name = "";

    if (isset($_POST['submit'])) {

        //Check if empty labels form
        if (empty($_POST['name'])) {
            $userError = "The 'name' is required.";
            echo '<script>window.location="#registrer"</script>';
        } else { $name = $_POST['name']; }

        if (empty($_POST['email'])) {
            $emailError = "El 'Email' es requerido.";
            echo '<script>window.location="#registrer"</script>';
        } else { 
            $email = $_POST['email'];
            //Check only contain letters and whitespace.
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $emailError = "El 'Email' is not valid. ";
                echo '<script>window.location="#registrer"</script>';
            }
        }                           

        if (empty($_POST['password'])) {
            $passwordError = "The 'password' is requiered.";
            echo '<script>window.location="#registrer"</script>';
        } else { 
            $password = $_POST['password']; 
        }

    }
        //Check if correctly filled
        if ($name && $username && $email && $password) {

            require('connect.php');

            //Query SQL
            $sql = "SELECT * FROM user WHERE username='$username'"; //String SQL
            $query = mysqli_query($ConDB, $sql);//Query
            //Securite
            $username = mysqli_real_escape_string($ConDB, $username);
            $password = mysqli_real_escape_string($ConDB, $username);
            $passw = sha1($password);//For securite.
            $name = mysqli_real_escape_string($ConDB, $username);
            $email = mysqli_real_escape_string($ConDB, $username);

            if ($existe = mysqli_fetch_object($query)) {

                $usernameError = "The 'Username' is already exists.";
                echo '<script>window.location="#registrer"</script>';

            } else {

                $sql = "INSERT INTO user (username, password, email, name) VALUES ('$username', '$passw', '$email', '$name')";

                mysqli_query($ConDB, $sql);


                $okmsg = "Register with succes.";

                mysqli_close($ConDB);//Close conexion.

                echo '<script>window.location="#registrer"</script>';
            }



        }

?>

<a name="registrer"></a>

<form action="" method="POST">

    <p><label>name&nbsp;&nbsp; : </label>
     <input id="password" type="text" name="name" placeholder="name" /></p>
     <?php echo $nameError; ?>

    <p><label>User Name : </label>
    <input id="username" type="text" name="username" placeholder="username" /></p>
    <?php echo $usernameError; ?>

    <p><label>E-Mail&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; : </label>
     <input id="password" type="email" name="email"/></p>
     <?php echo $emailError; ?>

     <p><label>Password&nbsp;&nbsp; : </label>
     <input id="password" type="password" name="password" placeholder="password" /></p>
     <?php echo $passwordError; ?>


    <a class="btn" href="login.php">Login</a>
    <input class="btn register" type="submit" name="submit" value="Register" />
    <?php echo $okmsg; ?>
</form>
--
-- DATA BASE: `user`
-- 
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

CREATE TABLE user (
   id int(11) unsigned not null auto_increment primary key,
   name varchar(50) not null,
   email varchar(80) not null unique,
   username varchar(30) not null unique,
   password varchar(40) not null
)engine=InnoDB default charset=utf8 collate=utf8_general_ci;

答案 3 :(得分:0)

您可以尝试使用jQuery AJAX。

首先,将其添加到 registration.php 文件

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
    // when user submit the form
    $('form').on('submit', function(event){
        $.ajax({
            url: "check_username.php",
            type: "POST",
            dataType: "JSON",
            data: {
                username: $("#username").val() // get the value from username textbox
            },
            success: function(data){
                if(data.status == "exists"){
                    alert('Username already existed');
                }
                else{
                    $('form').submit();
                }
            },
        });
        event.preventDefault();
    });
</script>


现在您的 registration.php 文件将如下所示

  

和registration.php

<form action="" method="POST">
    <p>
        <label>name&nbsp;&nbsp; : </label>
        <input id="password" type="text" name="name" placeholder="name" />
    </p>
    <p>
        <label>User Name : </label>
        <input id="username" type="text" name="username" placeholder="username" />
    </p>
    <p>
        <label>E-Mail&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; : </label>
        <input id="password" type="email" name="email"/>
    </p>
    <p>
        <label>Password&nbsp;&nbsp; : </label>
        <input id="password" type="password" name="password" placeholder="password" />
    </p>
    <a class="btn" href="login.php">Login</a>
    <input class="btn register" type="submit" name="submit" value="Register" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
    // when user typing in 'username' textbox
    $('form').on('submit', function(event){
        $.ajax({
            url: "check_username.php",
            type: "POST",
            dataType: "JSON",
            data: {
                username: $("#username").val() // get the value from username textbox
            },
            success: function(data){
                if(data.status == "exists"){
                    alert('Username already existed');
                }
                else{
                    $('form').submit();
                }
            },
        });
        event.preventDefault();
    });
</script>


然后创建名为 check_username.php 的php文件,以检查用户提交的用户名(如果用户已存在于数据库中或仍然可用)。

  

check_username.php

<?php
    // Check if 'username' textbox is not empty
    if(!empty($_POST['username'])){
        $username = trim(mysqli_real_escape_string($_POST['username']));
        // Check the database if the username exists
        $query = "SELECT username FROM `user` WHERE username = '".$username."'";
        $result = mysqli_query($query);
        if(mysqli_num_rows($result) > 0){
            // if username already exist
            // insert into array, to be sent to registration.php later
            $response['status'] = 'exists';
        }
        else{
            // if username available
            $response['status'] = 'available';
        }
    }

    header('Content-type: application/json');
    echo json_encode($response);
    exit;
?>


以下是它的工作原理:
1.当用户单击注册按钮时,jQuery将调用 check_username.php

2.现在在 check_username.php 中,如果提交的用户名已经存在或仍然可用,它将检查数据库。

3.无论结果是存在还是可用, check_username.php 都会将结果发送回 registration.php ,因为字符串包含'exists'或'available'。

4. registration.php 现在获得结果并检查 check_username.php 发送的结果,如果它包含'exists'或'available'。如果字符串是“存在”,则将触发警报。如果字符串是“可用的”,则表单将被提交。