Saturday, March 8, 2014

Sending Data to MySQL Database Using PHP With Unity3D Game Engine

Hello everyone, In this article, I will share an Unity3D game engine example with you guys. We will imagine that we have got a game has been played and opened score scene. This step will be sharing platform for scores between users. At this stage score information will be taken and posted to PHP page for sending to MySQL database. For these steps, we'll need these digital materials and tools given below:
  • An empty scene in the Unity3D game engine and Main Camera
  • An JavaScript scripting file for posting data to PHP page
  • An table named highscore in the MySQL database
  • An Server that can work PHP programming language

First, we will add javascript file to Main Camera Inspector in the empty scene.

function send(data, username) {
    var form = new WWWForm();
    form.AddField("action", "send");
    form.AddField("score", data);
        form.AddField("username", username);
    var url = "http://localhost/unity/send.php";
    var w = WWW(url, form);
    yield w;

send(999, "phpservisi");

Codes given above send score information to send.php PHP file for saving MySQL database. WWWForm object has been created for outside connection. This object has got action attribute and send value. This value will be used in PHP file as a condition to send MySQL database. score attribute's value is going to share with other players. For that reason we need all attribute, variable and values. Url variable shows us what will we use for target POST URL information.

Just remember that you have to add this JavaScript file to Main Camera's Inspector part using Add Component.

Now, we can finally create our PHP file for saving datas to MySQL DATABASE. But first create highscore table in the MySQL: 

Let's get PHP file:

if($_REQUEST['action']=="send") {
$score = $_REQUEST['score'];
$username = $_REQUEST['username'];
$query = "INSERT INTO `highscore` (username, score) VALUES ('$username', '$score')";

From on now, we can send our score data to PHP file for saving database, when the game run. send function helps us to POST datas. username and score datas are used via JavaScript file in the Unity3D game engine. $score and $username variables came from JavaScript file as you have known. After this we just use
SQL query.

As result, we have just done sent datas to MySQL database using PHP programming language with Unity3D game engine JavaScript codes. This article will be helpful. Because if you want to create a game for muliplatform, you have to develop multiplatform.

See you guys next articles!