How would one connect a Unity game to a Database to store simple amounts of data?

Hey there.

As a Project for this university's semester, we were instructed to develop a Unity game and a Companion App for Android.
Both must connect to a Database and communicate with each other.
For our Project, I just need to have User Authentication in Unity as well as insert some numbers into the Database so my Companion App can retrieve and use them (amount of items collected in Unity, amount of deaths, etc).

We were told to use NodeJS and MongoDB as it was easier (?). Now, I worked with both of them a few months ago to develop a website but after doing some research, I have no clue on how to implement a MongoDB and NodeJS server in Unity. Seems like there isn't an easy way to do it since I have a restrict programming knowledge when it comes to the server side.

I'm getting desperate as the delivery date is getting close.

Are there any easy-to-implement options so I can retrieve, insert data and have User Authentication in both Unity and Companion App?

Thank you in advance.

EDIT: Forgot to mention we don't know PHP. We were only teached HTML and Javascript during the website semester.

1 Like

Providing you don't need stream data, where latency is critical, you can use simple PHP request via www, to send / receive data.
You keep all security on PHP side.

I forgot to mention we weren’t given any bases on PHP. Apologies for not mentioning it on the main post. Will update accordingly.

Thank you for your reply.

Its fine.
But I suggest to grab SQL with PhP server. PHP is not that hard at all, if you grasp basics.

In my opinion, it is much harder to build website with NodeJS than PHP.
However, with NodeJS, you can make nice multiplayer games, with connections based on sockets.

I assume you are learning HTML5 ? Or just raw HTML and Javascript, without CSS?

1 Like

Your going to need to know c# at the very least to dive into unity I am afraid.

1 Like

Yep, that assuming OP has some basics knowledge, or intention to learn c#. But it will not be 5 min job, juts to be aware, to be on safe side.

Oh I do know C#. I’ve been at it for the past months. C# is not the problem. The problem was not knowing PHP but I opted for learning the basics and give it a try following @Antypodish 's advice. Everything looking good so far.

Thank you!

I have a new issue that came up today.
In the Unity game for PC I have 3 food items spread throughout the levels that are exactly the same, only varying on the sprites. The Companion App allows the users to unlock new themes and equip them in the Unity game (PC). Doing this will change those 3 sprites according to the theme chosen by the Player.

What would be the best way to tell Unity, through MySQL and PHP, if a Player has unlocked or equipped a new theme?

Thank you in advance.

On data base side, you would have players, themes and players related theme table, with.
Players, if more than one, will store basics information about each player. ID, loging data, etc.

On themes side, you have theme ID and related theme data.

One player related theme table, you need column for player ID, column for theme ID. That is simplest form.
But you can expand by adding other data, including column storing IsThemeActive. Etc.

PHP side will need add, or remove references of player to theme, from player related theme table.
Alternatively just toggle IsThemeActive cell, for matching player / theme.

In php you have listener by using GET, to receive player ID following by its data in same request.
Something like for example

If you got only one player, then you can shrink to

But for more players, you may also need authentication hash code. That providing, you concerns about something hacking application, and changing ID in Unity application registry.

Either way these request will be sent from Unity.

That's pretty much minimum what you may need.

Thank you! Will give a look and update accordingly during the following days. Again, thank you very much!

1 Like

Here I am again, @Antypodish !
I’ve been following this youtube series
and got everything working. When implementing it on my Project, the login and register system work but not the updating of the queries.

Here are my scripts:

Unity - Player.cs

public void prepareSaveData()
        totalTime = Time.timeSinceLevelLoad;

        DatabaseManager.totalWeight = (int) currentWeight;
        DatabaseManager.totalTime = (int) totalTime;


        totalTime = 0;
        Debug.Log("button hit");

    public void CallSaveData()

    IEnumerator SavePlayerData()
        WWWForm form = new WWWForm();
        form.AddField("name", DatabaseManager.username);
        form.AddField("totalDeaths", 2);
        form.AddField("totalPlays", 1);
        form.AddField("totalWeight", 1);
        form.AddField("totalTime", 2);

        WWW www = new WWW("http://localhost/pathofbuddhadatabase/savedata.php", form);
        yield return www;

        if (www.text == "0")
            Debug.Log("Game Saved");
            Debug.Log("Save failed. Error #" + www.text);

Unity - DatabaseManager.cs

public static string username;
    public static int totalDeaths;
    public static int totalPlays;
    public static int totalWeight;
    public static int totalTime;

    public static bool LoggedIn { get { return username != null; } }

    public static void LogOut()
        username = null;

PHP - savedata.php


    $con = mysqli_connect('localhost', 'root', 'root', 'pathofbuddhadatabase');

    if(mysqli_errno()) {
        echo "1: Connection to database failed";

    $username = $_POST["name"];
    $newTotalDeaths = $_POST["totalDeaths"];
    $newTotalWeight = $_POST["totalWeight"];
    $newTotalTime = $_POST["totalTime"];
    $newTotalPlays = $_POST["totalPlays"];

    $nameCheckQuery = "SELECT username FROM users WHERE username = '" . $username . "';";

    $nameCheck = mysqli_query($con, $nameCheckQuery) or die("2: Name check query failed");

    if(mysqli_num_rows($nameCheck) != 1) {
        echo "3: A User with that Username already exists or you aren't registered";

    /*$updateQuery = "UPDATE users SET totalDeaths = " . $newTotalDeaths . ",
                                     totalWeight = " . $newTotalWeight . ",
                                     totalTime = " . $newTotalTime . ",
                                     totalPlays = " . $newTotalPlays . " WHERE username = '" . $username . "';";*/

    $updateQuery = "UPDATE users SET totalDeaths = $newTotalDeaths,
                                    totalWeight = $newTotalWeight,
                                    totalTime = $newTotalTime,
                                    totalPlays = $newTotalPlays WHERE username = $username";
    mysqli_query($con, $updateQuery) or die ("7: Save query failed");

    echo "0";

I linked the Player.cs’ prepareSaveData() to a button and it runs every function but no error or success message is returned nor the MySQL database is updated.

Any idea what the problem might be?

Can you try send save request via web browser, to see if yo got php side working correctly?

When I post “http://localhost/pathofbuddhadatabase/savedata.php” on a browser it prints “3: A User with that Username already exists or you aren’t registered” which I believe it isn’t enough since you’re trying to reach to the bottom of the php code.
If so, could you give me guidelines on how to perform it?

Thank you for your time.

Edit: Ok this is odd. I swear I didn’t touch anything but the MySQL just updated. So weird.

Edit2: The values are being correctly updated in the database but Unity is not printing the success message.

You can try create simple php, or even html page, with minimalistic html form, of few inputs and submit button, which sends form as POST.

Your simple form fields should match your php structure.
This page would be probably few lines long at most.

Try and see what you can come up with.
Alternatively, create copy of your php file, lets say add postfix 2 to file name, and replace POST with GET. Then you call that file via web browser address, with request, using *.php?totalDeaths=3&totalTime=4& etc. Just as an example.

I did as you said and everything worked perfectly. I started digging on the Unity Forums and one thread came up saying that it couldn’t print a www.text since you were asking for it before the queries and such were done.

I added some lines of code and everything works now! Thank you!

1 Like

Well done.

1 Like

What if I wanted to stream data?