Last time, we set up everything we needed to add a new user account to our database. This time, we’ll set up everything we need to let a user log in to our game. Compared to the last one, this should be a pretty simple operation now that we know the basics. Let’s start with our PHP script for getting the user information we need to log a user in:
I’ve called this script GetUser.php and once again placed it in the htdocs folder of our XAMPP install. If you examine the script, you’ll see a few similarities to AddUser.php, namely the first two lines. You’ll need to replace the username, password and databasename fields with your own information, just like last time. Also, we are passing the username into this script as a GET request. This time instead of our $query being an INSERT statement, it is a SELECT statement selecting the row from the table where the username column matches the passed in value. We also don’t need to hash to verify as we aren’t inserting information or modifying the database in any way, just retrieving information. The information we’re after is just the password column in that one row that our SELECT statement should return, and all we need to do with it is echo it so it displays as text on our webpage and can be retrieved from Unity. If you want to test this script really quickly, go to https://localhost/GetUser.php?username=username, where the second username is a user in your users database. You should get a string of characters that looks like an encoded password if like me you properly encrypted your users passwords.
Let’s move on to the code we need to add to Unity to hook up to this. I’ve added the following function to the MainMenuManager script we created last time:
All it does is check whether the input fields are empty and if not tells our DatabaseConnection class to attempt a log in. Here’s the code added to DatabaseConnection to implement the log in:
Similar to the last functions we made when creating the DatabaseConnection class, this uses a coroutine to get information from our web server. However, all we’re interested in this time is the password for that particular user. We have to pass the username to the PHP script, but that’s it this time. Since I encrypted their password before adding it to the database, I have to remember to decrypt it again before checking against what the user entered. I’ve used Debug statements to show whether or not the login was successful, but don’t let that stop you from doing more than that!
All right, that wasn’t so bad! Now you’ve got a web server and MySQL server set up on your machine, a users database set up on your MySQL server, and some scripts that allow you to add users and check a user’s login information. This is truly only the beginning of what you can do with MySQL and Unity, but it’s a solid foundation for moving forward. Enjoy!