[Unity+MySQL] Realize the registration and login system (upgraded version)


Following the system defects mentioned in the previous article, this article will be upgraded to solve it.

1 UI interface redesign

Problem : The registration interface and the login interface are the same interface, causing the user to click to log in after entering the user password for registration.

Solution : Create a registration interface and a login interface in the same scene, and use SetActive to control the display and hiding of the UI after successful registration/login.

The overall UI framework is built as shown in the figure below:
insert image description here

1.1 Registration interface

insert image description here

Among them, the blue text at the bottom is used as a prompt message to prompt the user's registration status.

1.2 Login interface

insert image description here

Among them, the purple text at the bottom is used as a prompt message to prompt the user's registration status.

1.3 Interactive implementation

Since registration and login use the same input box here, the input box is cleared after login or registration. There is one more thing to pay attention to here. It is necessary to judge whether the username and password are empty when logging in and registering. If it is empty, a prompt that it cannot be empty is given.

Interactive function code:

using UnityEngine;
using UnityEngine.UI;
using MySql.Data.MySqlClient;
using System;

public class DatabaseManager : MonoBehaviour
{
    
    
    // 数据库连接相关变量
    private MySqlConnection connection;
    private string serverName = "localhost";
    private string dbName = "UnityGame";	// 数据库名
    private string userName = "root";		// 登录数据库的用户名
    private string password = "123456";		// 登录数据库的密码
    private string port = "3306";           // MySQL服务的端口号

    // 注册UI和登录UI
    public GameObject RegisterUI;
    public GameObject LoginUI;

    // 用户名输入框和密码输入框
    public InputField usernameInputField;
    public InputField passwordInputfield;

    // 注册消息和登录消息
    public Text registerMessage;
    public Text loginMessage;

    void Start()
    {
    
    
        // 初始化UI状态
        LoginUI.SetActive(true);
        RegisterUI.SetActive(false);

        // 连接数据库
        string connectionString = "Server=" + serverName + ";Database=" + dbName + ";Uid=" + userName
                                  + ";Pwd=" + password + ";Port=" + port + ";";
        connection = new MySqlConnection(connectionString);
        connection.Open();
        Debug.Log("连接数据库成功");
    }

    // 注册逻辑
    public void OnRegister()
    {
    
    
        // 从输入框获取用户名和密码
        string username = usernameInputField.text;
        string password = passwordInputfield.text;

        if (username == "" || password == "")
        {
    
    
            registerMessage.text = "账号或密码不能为空";
        }

        else
        {
    
    
            // 构造插入数据的SQL语句,并将用户名和密码赋值给参数
            string query = "INSERT INTO usersinfo(username, password) VALUES (@username, @password)";
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.Parameters.AddWithValue("@username", username);
            cmd.Parameters.AddWithValue("@password", password);

            // 执行SQL语句,获取影响的行数
            int rowsAffected = cmd.ExecuteNonQuery();

            // 根据影响的行数给出注册成功或失败的消息,并清空输入框
            if (rowsAffected > 0)
            {
    
    
                Debug.Log("注册成功");
                registerMessage.text = "注册成功";
            }
            else
            {
    
    
                Debug.Log("注册失败");
                registerMessage.text = "注册失败";
            }
            usernameInputField.text = "";
            passwordInputfield.text = "";
        }
    }

    // 登录逻辑
    public void OnLogin()
    {
    
    
        // 从输入框获取用户名和密码
        string username = usernameInputField.text;
        string password = passwordInputfield.text;

        if(username == "" || password == "")
        {
    
    
            loginMessage.text = "账号或密码不能为空";
        }

        else
        {
    
    
            // 构造查询数据的SQL语句,并将用户名和密码赋值给参数
            string query = "SELECT COUNT(*) FROM usersinfo WHERE username=@username AND password=@password";
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.Parameters.AddWithValue("@username", username);
            cmd.Parameters.AddWithValue("@password", password);

            // 执行SQL语句,获取查询结果
            object result = cmd.ExecuteScalar();
            int count = Convert.ToInt32(result);

            // 根据影响的行数给出注册成功或失败的消息,并清空输入框
            if (count > 0)
            {
    
    
                Debug.Log("登录成功");
                loginMessage.text = "登录成功";
            }
            else
            {
    
    
                Debug.Log("登录失败");
                loginMessage.text = "登录失败";
            }
            usernameInputField.text = "";
            passwordInputfield.text = "";
        }
    }
}

Related variable binding:
insert image description here
Go to the registered button event binding:
insert image description here

Go to login button event binding:
insert image description here

2 The registration function is perfect

Problem 1 : The user information is not verified when the user registers. For example, a user should be prompted when registering with the same user name, and the user name or password should also be prompted if the user name or password is empty.
Problem 2 : The registration time when the user registers is not added to the user table.
Question 3 : The password entered by the user when registering is stored in the database in plain text, which is not safe.

2.1 Determine whether the user name entered by the user is the same as that in the database

Use the SQL query statement to query whether there is a user record with the given username in the database, check the query result and return the information entered by the user as needed. If the value of the count variable is 0, it means that there is no user record with that username in the database, and the registration process can continue. If the value of the count variable is greater than 0, it means that the user name is already occupied, and the user needs to be prompted to choose a different user name.

Code implementation of the modified registration function:

	// 注册逻辑
    public void OnRegister()
    {
    
    
        // 从输入框获取用户名和密码
        string username = usernameInputField.text;
        string password = passwordInputfield.text;

        if (username == "" || password == "")
        {
    
    
            registerMessage.text = "账号或密码不能为空";
        }

        else
        {
    
    
            // 检查数据库中是否存在具有给定用户名的用户记录
            string query1 = "SELECT COUNT(*) FROM usersinfo WHERE username = @Username";
            MySqlCommand cmd1 = new MySqlCommand(query1, connection);
            cmd1.Parameters.AddWithValue("@Username", username);
            int count = Convert.ToInt32(cmd1.ExecuteScalar());

            // 根据查询结果提示用户
            if (count > 0)
            {
    
    
                Debug.Log("用户名已存在,请选择不同的用户名!");
                registerMessage.text = "用户名已存在,请选择不同的用户名!";
            }
            else
            {
    
    
                // 构造插入数据的SQL语句,并将用户名和密码赋值给参数
                string query2 = "INSERT INTO usersinfo(username, password) VALUES (@username, @password)";
                MySqlCommand cmd2 = new MySqlCommand(query2, connection);
                cmd2.Parameters.AddWithValue("@username", username);
                cmd2.Parameters.AddWithValue("@password", password);

                // 执行SQL语句,获取影响的行数
                int rowsAffected = cmd2.ExecuteNonQuery();

                // 根据影响的行数给出注册成功或失败的消息
                if (rowsAffected > 0)
                {
    
    
                    Debug.Log("注册成功");
                    registerMessage.text = "注册成功";
                }
                else
                {
    
    
                    Debug.Log("注册失败");
                    registerMessage.text = "注册失败";
                }
            }
            //清空输入框
            usernameInputField.text = "";
            passwordInputfield.text = "";
        }
    }

2.2 Update the current time to the current registration time column of the user table

Set the createtime column type of usersinfo to timestamp, and modify its default value to CURRENT_TIMESTAMP.
insert image description here
The result of inserting into the database after successful registration:
insert image description here

2.3 Encrypt the registration password entered by the user with hash

In the C# script, the results of user registration and login are encrypted by hash, so that when comparing, the encrypted ciphertext is used for comparison.

Modified part of the code:

using System.Security.Cryptography;
    
	// 加密密码
    private static string HashPassword(string password)
    {
    
    
        SHA256Managed crypt = new SHA256Managed();
        StringBuilder hash = new StringBuilder();
        byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(password));
        foreach (byte theByte in crypto)
        {
    
    
            hash.Append(theByte.ToString("x2"));
        }
        return hash.ToString();
    }

	// 注册逻辑
    public void OnRegister()
    {
    
    
        // 从输入框获取用户名和密码
        string username = usernameInputField.text;
        //使用哈希进行加密
        string password = HashPassword(passwordInputfield.text);
        
        //省略
    }

	// 登录逻辑
    public void OnLogin()
    {
    
    
        // 从输入框获取用户名和密码
        string username = usernameInputField.text;
        //使用哈希进行加密
        string password = HashPassword(passwordInputfield.text);

        //省略
    }

Among them, the closing database is added, and the database is closed after the user logs in successfully.

The result of inserting into the database after successful registration:
insert image description here

3 The login function is perfect

Problem : When the user logs in, there is no prompt for a specific error, whether it is due to a wrong username and password or the user is not registered, it will prompt "login failed".

The code implementation of the modified login function:

	// 登录逻辑
    public void OnLogin()
    {
    
    
        // 从输入框获取用户名和密码
        string username = usernameInputField.text;
        //使用哈希进行加密
        string password = HashPassword(passwordInputfield.text);

        if (username == "" || password == "")
        {
    
    
            loginMessage.text = "账号或密码不能为空";
        }
        else
        {
    
    
            // 构造查询数据的SQL语句,并将用户名和密码赋值给参数
            string query = "SELECT COUNT(*) FROM usersinfo WHERE username=@username AND password=@password";
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.Parameters.AddWithValue("@username", username);
            cmd.Parameters.AddWithValue("@password", password);

            // 执行SQL语句,获取查询结果
            object result = cmd.ExecuteScalar();
            int count = Convert.ToInt32(result);

            // 根据影响的行数给出注册成功或失败的消息,并清空输入框
            if (count > 0)
            {
    
    
                Debug.Log("登录成功");
                loginMessage.text = "登录成功";
            }
            else
            {
    
    
                // 根据查询结果给出不同的提示消息
                string errorMessage;
                query = "SELECT COUNT(*) FROM usersinfo WHERE username=@username";
                cmd = new MySqlCommand(query, connection);
                cmd.Parameters.AddWithValue("@username", username);
                result = cmd.ExecuteScalar();
                count = Convert.ToInt32(result);
                if (count == 0)
                {
    
    
                    errorMessage = "用户名不存在";
                }
                else
                {
    
    
                    errorMessage = "密码错误";
                }

                Debug.Log("登录失败:" + errorMessage);
                loginMessage.text = errorMessage;
            }
            usernameInputField.text = "";
            passwordInputfield.text = "";
        }
    }

4 Overall function flow chart

insert image description here

5 Function Demo

Fill in the user name and password to log in → the user name does not exist → go to register → fill in the user name and password to register → registration is successful:

Please add a picture description

Register with the same username→username already exists→login→enter another username→username does not exist→enter correct username and wrong password→wrong password→enter correct username and correct password→login successfully:

Please add a picture description
Data in the UsersInfo data table:
insert image description here

Guess you like

Origin blog.csdn.net/qq_41084756/article/details/130262778