📜 ⬆️ ⬇️

Unity3D and MySQL

Probably everyone who made a game for a social network or just an online game was faced with the problem of connecting and saving data to the database. In this article I will try to describe in detail how to establish a connection and transfer data to the MySQL database using PHP.

So let's get started, first create a script in Unity C #, name it MysqlConnect and enter the following code into it:

using UnityEngine; using System.Collections; public class MysqlConnect : MonoBehaviour { private string username = ""; //    private string pswd = ""; //    private string email = ""; //     private string url = "http://www.localhost.ru/habr/connect.php"; //    // ,       void Connect() { WWWForm form = new WWWForm(); //   //     form.AddField("username", username); form.AddField("password", pswd); form.AddField("email", email); //   WWW connect = new WWW(url, form); //    if (connect.isDone) { //     Debug.Log(connect.text); } //     else if (connect.error == null) { //    Error Debug.Log("Error"); } } //  OnGUI() void OnGUI() { //       username = GUI.TextField(new Rect(Screen.width/2-100, Screen.height/2-100, 200, 20), username, 12); //      pswd = GUI.TextField(new Rect(Screen.width/2-100, Screen.height/2-75, 200, 20), pswd, 12); //       email = GUI.TextField(new Rect(Screen.width/2-100, Screen.height/2-50, 200, 20), email, 50); //     if (GUI.Button(new Rect(Screen.width/2-100, Screen.height/2-25, 200, 20), "Connect")) { Connect(); } } } 

')
In this script, a request is made to the PHP script and the data entered by the user is transmitted to it.

Now, let's create a PHP script and name it connect.php:

 <?php //  $username = $_REQUEST['username']; $password = $_REQUEST['password']; $email = $_REQUEST['email']; $host = 'localhost'; //     $user = 'root'; //     $password = ''; //    $db = 'habr'; //      $table = 'users'; //     mysql_connect($host, $user, $password) or die(mysql_error()); //  mysql mysql_select_db($db); //   $password = md5($password); //  //       mysql_query("INSERT INTO `users` VALUES ('{$username}', '{$password}', '{$email}')") or die (mysql_error()); //  Done echo "Done"; ?> 


This script takes data from the engine and puts it into the MySQL database. Please note that the name of the PHP script (connect.php) must match the name of the script in the value of the url variable. It seems that this is all ... I hope this information has become useful for anyone.
This is my first article, I hope I described everything in detail and you solved your problem.

Source: https://habr.com/ru/post/187394/


All Articles