PHP和MySQL-检查用户名是否已被占用 [英] PHP and MySQL - Check if username is already taken

查看:79
本文介绍了PHP和MySQL-检查用户名是否已被占用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在的问题是,代码无法检查用户名是否已被使用,是否有任何代码可以检查用户名是否已在数据库中?

The problem now is, the code couldn't check if the username is already taken, is there any code that can check the username is already taken in the database?

我正在尝试一些代码,然后可能也在Stack Overflow中对此问题进行了搜索.我已经尝试过此解决方案,但显然它给了我错误.当我尝试过时,警告:

I am experimenting with some of my codes then probably searched it also in Stack Overflow about this issue. I've tried this solution but apparently it gives me errors. When I've tried it, the warning:

mysql_query()期望参数2为资源,对象在 C:...在线...

mysql_query() expects parameter 2 to be resource, object given in C:... on line ...

和问题

mysql_num_rows()期望参数1为资源,在中给出null C:...在线...

mysql_num_rows() expects parameter 1 to be resource, null given in C:... on line ...

我实际上是在寻找解决此问题的方法或有关如何解决此问题的教程.

I am actually looking for a solution for this problem or a tutorial how to solve this problem.

我的代码:

<?php
    require_once("functions.php");
    require_once("db-const.php");
    session_start();
    if (logged_in() == true) {
        redirect_to("profile.php");
    }
?>
<?php
 ?>
<html>
<head>
    <title>Prospekt Member Area</title>
</head>
<body>
<h1> Register Here </h1>
<h2>&copy; Kirk Niverba</h2>
<hr />
<!-- The HTML registration form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
    Username: <input type="text" name="username" /><br />
    Password: <input type="password" name="password" /><br />
    First name: <input type="text" name="first_name" /><br />
    Last name: <input type="text" name="last_name" /><br />
    Email: <input type="type" name="email" /><br />

    <input type="submit" name="submit" value="Register" />
    <a href="login.php">Already have an account?</a>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['first_name']) || empty($_POST['last_name']) || empty($_POST['email'])) {
        echo "Please fill all the fields!";
    }
elseif (isset($_POST['submit'])) {
## connect mysql server
    $mysqli = new mysqli(localhost, root, "", loginsecure);
    # check connection
    if ($mysqli->connect_errno) {
        echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
        exit();
    }
## query database
    # prepare data for insertion
    $username   = $_POST['username'];
    $mainpass = $_POST['password'];
    $password   = hash('sha256', $mainpass);
    $first_name = $_POST['first_name'];
    $last_name  = $_POST['last_name'];
    $email      = $_POST['email'];

    # check if username and email exist else insert
    // u = username, e = emai, ue = both username and email already exists
    $user = $_POST['username'];
  $usernamecheck=mysql_query("SELECT username FROM users WHERE username='$user'", $mysqli);
        if (mysql_num_rows($usernamecheck)>=1){
    echo $user." is already taken";
 }
    else{
        # insert data into mysql database
        $sql = "INSERT  INTO `users` (`id`, `username`, `password`, `first_name`, `last_name`, `email`)
                VALUES (NULL, '{$username}', '{$password}', '{$first_name}', '{$last_name}', '{$email}')";

        if ($mysqli->query($sql)) {
            header("Location: checklogin.php?msg=Registered Successfully!");
        } else {
            echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
            exit();
        }
    }
}
}
?>
<hr />
</body>
</html>

推荐答案

作为如何使用准备好的语句的示例,您可以使用以下语句(未经测试的btw)

As an example of how to use prepared statements you might be able to make use of the following ( not tested btw )

在原始代码中,您在输出html代码后发送了标头-除非您使用输出缓冲,否则这将导致错误,因此我在生成任何html内容之前将所有相关的PHP代码移了,如果以后有任何错误输出它们.

In the original code you were sending headers after outputting html code - this will cause an error unless you use output buffering so I moved all the relevant PHP code before any html content is generated and if there are any errors output them later.

我还注意到,没有引用mysqli连接的参数-如果将这些参数定义为常量,那就没问题了,否则也会产生错误.

I noticed also that the parameters for the mysqli connection were not quoted - if these were defined as constants then that would be fine, otherwise that too would have generated errors.

保留mysqlipdo-当您采用我试图在此处显示的准备好的语句时,可以更好地保护您的网站免受恶意用户的侵害.

Keep to mysqli or pdo - as you can better protect your sites from malicious users when you adopt prepared statements like I have attempted to show here.

<?php
    require_once("functions.php");
    require_once("db-const.php");
    session_start();

    if (logged_in() == true) {
        redirect_to("profile.php");
    }

    $errors=array();

    if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {

        if( isset( $_POST['username'], $_POST['password'], $_POST['first_name'], $_POST['last_name'], $_POST['email'] ) ) {

            $username   = !empty( $_POST['username'] ) ? $_POST['username'] : false;
            $mainpass   = !empty( $_POST['password'] ) ? $_POST['password'] : false;
            $password   = !empty( $mainpass ) ? hash('sha256', $mainpass) : false;
            $first_name = !empty( $_POST['first_name'] ) ? $_POST['first_name'] : false;
            $last_name  = !empty( $_POST['last_name'] ) ? $_POST['last_name'] : false;
            $email      = !empty( $_POST['email'] ) ? $_POST['email'] : false;

            if( $username && $password ){
                $mysqli = new mysqli( DB_HOST, DB_USER, DB_PASS, DB_NAME );
                if( $mysqli->connect_errno ) {
                    $errors[]=$mysqli->connect_error;
                } else {

                    /* Assume all is ok so far */
                    $sql='select username from users where username=?';
                    $stmt=$mysqli->prepare($sql);
                    $stmt->bind_param('s',$username);
                    $stmt->execute();

                    $stmt->bind_result( $found );
                    $stmt->fetch();

                    if( !$found ){
                        /* username is not alreday taken */

                        $sql='insert into `users` (`username`,`password`,`first_name`,`last_name`,`email`) values (?,?,?,?,?);';
                        $stmt=$mysqli->prepare( $sql );
                        $stmt->bind_param('sssss',$username,$password,$first_name,$last_name,$email);
                        $stmt->execute();

                        header("Location: checklogin.php?msg=Registered Successfully!");
                    } else {
                        /* username is taken */
                        $errors[]='Sorry, that username is already in use.';
                    }
                }   
            }
        } else {
            $errors[]='Please fill in all details';
        }
    }
?>
<html>
    <head>
        <title>Prospekt Member Area</title>
    </head>
    <body>
        <h1> Register Here </h1>
        <h2>&copy; Kirk Niverba</h2>
        <hr />

        <!-- The HTML registration form -->
        <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
            Username: <input type="text" name="username" /><br />
            Password: <input type="password" name="password" /><br />
            First name: <input type="text" name="first_name" /><br />
            Last name: <input type="text" name="last_name" /><br />
            Email: <input type="type" name="email" /><br />

            <input type="submit" name="submit" value="Register" />
            <a href="login.php">Already have an account?</a>
        </form>
        <?php
            if( !empty( $errors ) ){
                echo implode( '<br />', $errors );
            }
        ?>
        <hr />
    </body>
</html>

这篇关于PHP和MySQL-检查用户名是否已被占用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆