PHP到mySQL检查用户是否存在

时间:2015-07-29 18:32:15

标签: php mysql authentication user-controls

我有一个脚本,可以从iOS设备更新/创建用户。现在我想让脚本也检查用户是否已经存在于数据库中。我现在要将此限制为用户名,因此可能只存在一个唯一的用户名。我的PHP中有一个if语句,但我无法让它工作 - 请帮助:)。

    <?php

    header('Content-type: application/json');
    if($_POST) {
        $username   = $_POST['username'];
        $password   = $_POST['password'];

        if($username && $password) {

                $db_name     = 'dbname';
                $db_user     = 'dbuser';
                $db_password = 'dbpass';
                $server_url  = 'localhost';

                $mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);

            $userexists = mysql_query("SELECT * FROM users WHERE username='$username'"); 

            /* check connection */
            if (mysqli_connect_errno()) {
                error_log("Connect failed: " . mysqli_connect_error());
                echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
            }

            if(mysql_num_rows($userexists) != 0) { 
                echo '{"success":0,"error_message":"Username Exist."}';
            } 

            else {

                $stmt = $mysqli->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
                $password = md5($password);

                $stmt->bind_param('sss', $username, $password, $email);

                    /* execute prepared statement */
                $stmt->execute();

                if ($stmt->error) {error_log("Error: " . $stmt->error); }

                $success = $stmt->affected_rows;

                    /* close statement and connection */
                $stmt->close();

                    /* close connection */
                $mysqli->close();
                error_log("Success: $success");

                        if ($success > 0) {
                        error_log("User '$username' created.");
                        echo '{"success":1}';
                        } 
                        else {
                        echo '{"success":0,"error_message":"Username Exist."}';
                        }
            }

        } 
        else {
            echo '{"success":0,"error_message":"Passwords does not match."}';
        }
    } 
    else {
        echo '{"success":0,"error_message":"Invalid Username."}';
    }
}   
else {
    echo '{"success":0,"error_message":"Invalid Data."}';
}
?>

1 个答案:

答案 0 :(得分:0)

在尝试插入SELECT之前,您可以username该表。如果它已经存在(=你有结果),你不要简单地插入。

更好的是,使用ON DUPLICATE IGNORE或类似的东西。