unity3d and php background simple interaction

Keywords: PHP Unity Database SQL

Environmental Science:
Unity2017.3.0f3
Mysql5.7.20
Wampserver64
Create a new folder named unity in the www directory of Wampserver64.

1. unity3d requests php by get

  1. Code on unity side
using UnityEngine;
using System.Collections;

public class phpUnity1 : MonoBehaviour
{
    private string url = "http://localhost/unity/phpunity1.php?id=1&cid=123456";  //url with get parameter id and cid

    void OnGUI()
    {
        if (GUILayout.Button("get php"))
        {
            StartCoroutine(OnGet());
        }
    }

    IEnumerator OnGet()
    {
        WWW www = new WWW(url);

        yield return www;

        if (www.error != null)
        {
            print("php Request error: Code is" + www.error);
        }
        else
        {
            print("php Request succeeded" + www.text);
        }
    }

}
   1. 2 php code (php name is phpunity1.php)
<?php  
    if(isset($_GET["id"])
        && isset($_GET["cid"]))
    {
        echo "get Request succeeded,id The value is:".$_GET["id"].",cid The value is:".$_GET["cid"];
    }
?>

result:

2. unity3d requests php through post

    2. 1 code on unity side
using UnityEngine;
using System.Collections;

public class phpUnity2: MonoBehaviour
{

    private string url = "http://localhost/unity/phpunity2.php";  //

    void OnGUI()
    {
        if (GUILayout.Button("Post php"))
        {
            StartCoroutine(OnGet());
        }
    }

    IEnumerator OnGet()
    {
        //form
        WWWForm form = new WWWForm();
        form.AddField("id", 1);
        form.AddField("cid", 123456);

        WWW www = new WWW(url, form);

        yield return www;

        if (www.error != null)
        {
            print("php Request error: Code is" + www.error);
        }
        else
        {
            print("php Request succeeded" + www.text);
        }
    }
}
    2. 2 php code (php name is phpunity2.php)
<?php 
    if(isset($_POST["id"])
        && isset($_POST["cid"]))
    {
        echo "post Request succeeded,id The value is:".$_POST["id"].",cid The value is:".$_POST["cid"];
    }    
?>

The results are as follows:

3. Background communication instance of unity3d and php

    3. 1. Simple UI interface

            3. 2 code on unity side
using UnityEngine;
using UnityEngine.UI;
using System.Collections;


public class login : MonoBehaviour
{
    public InputField userIdField;
    public InputField passwordField;
    public Text statusText;


    public Button loginBtn;
    private string userId = "";
    private string password = "";
    private string url = "http://localhost/unity/login.php";

    private void Awake()
    {
        loginBtn.onClick.AddListener(OnLogin);
    }
    public   void OnLogin()
    {
        userId = userIdField.text;
        password = passwordField.text;

        if (string.IsNullOrEmpty(userId)|| string.IsNullOrEmpty(password))
        {
            print("Account and password cannot be empty");

            return;
        }

        StartCoroutine(logining());
    }

    private IEnumerator logining()
    {
        WWWForm form = new WWWForm();

        form.AddField("userId", userId);
        form.AddField("password", password); 

        WWW www = new WWW(url, form);


        yield return www;

        if (www.error != null)
        {
            print("error is login:" + www.error);
            statusText.text = www.error + "...";
        }
        else
        {
            print(www.text);
            statusText.text = www.text;
        }

    }

}
    3. 3 PHP code

Here are two,
One is the operation code dbconfig.php of PHP to the database,
The second is login.php

dbconfig.php

<?php
    /****************************************************************************
    *    Description: encapsulation of database
     ****************************************************************************/

    class dbconfig{

        //Constructor
        function __construct()
        {
             if(!$this->mysqli = mysqli_connect($this->host, $this->user, $this->pwd))
            {
                die("Cant connect into database");        
            }
            else
            {

                     echo  "Successfully connected to database...<br />";
            }

            $this->select_db($this->db_name);        
        }

        //Destructor
        function __destruct()
        {
            mysqli_close($this->mysqli);
        }

        /*
        *    explain:    
        */
        public function get_mysql_handle()
        {
            return $this->mysqli;
        }

        /*
        *    explain:    
        */        
        public function select_db($_db)
        {
            if($this->mysqli != null)
            {
                if(mysqli_select_db($this->mysqli, $_db))
                {
                     echo  "Successfully connected to database...<br />";
                }
                else
                {
                    die("Cant connect into database");
                }
            }
        }        

        /*
        *    Note: no return value when executing an sql
        */
        public function execute($_sql)
        {
            if(empty($_sql))
            {
                echo "Parameter cannot be empty";
                return;
            }

            if(!mysqli_query($this->mysqli, $_sql)) 
            {

                  echo  "Execution failed...<br />";
            }
        }

        /*
        *    Description: execute a query statement and callback function
        */
        public function do_query($_sql, $query_callback = "")
        {
            if(empty($_sql))
            {
               echo  "Parameter cannot be empty";

                return;
            }

            if($result = mysqli_query($this->mysqli, $_sql)) 
            {
                $num_rows = $result->num_rows;
                if($num_rows > 0)
                {
                     while($row = $result->fetch_assoc())
                    {
                        if(!empty($query_callback))
                        {
                            call_user_func( $query_callback , $row );
                        }
                    }

                    return $num_rows;
                }
                else
                {
                    return 0;
                }

                mysqli_free_result($result);    
            }
            else
            {
               echo  "Execution failed...<br />";
            }
        }


        //Member variable
        private $host = "localhost";    //Database address
        private $user = "root";            //user name
        private $pwd = "123456";                //User password
        private $db_name = "test";        //data base
        private $mysqli = null;
    }
?>

login.php

<?php
    /****************************************************************************
    *    Description: log in
     ****************************************************************************/
    include_once "dbconfig.php";

    $dbcfg = new dbconfig();
    $password_db = "";

    if(isset($_POST["userId"]) && isset($_POST["password"]))
    {
        $password = $_POST["password"];

        $sql = "select * from tb1 where userid='".$_POST['userId']."'";
        if($dbcfg->do_query($sql, "login_callback") > 0)
        {
            if($password_db == $password)
            {

                echo "Login successful...".$_POST["userId"].",".$_POST["password"].",".$password_db;
            }
            else
            {

                 echo "Login failed 1...".$_POST["userId"].",".$_POST["password"].",".$password_db;
            }
        }
        else
        {

             echo "Login failed 2...".$_POST["userId"].",".$_POST["password"].",".$password_db;
        }
    }

    function login_callback($row)
    {
        global $password_db;
        $password_db = $row["password"];
    }
?>
    3. 4. Create a test data table in MySQL: (database name is test)
DROP TABLE IF EXISTS `tb1`;
CREATE TABLE `tb1` (
  `userid` varchar(30) NOT NULL,
  `password` varchar(50) NOT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `tb1` VALUES ('1', '123456');
INSERT INTO `tb1` VALUES ('2', '123456');
INSERT INTO `tb1` VALUES ('3', '123456');
INSERT INTO `tb1` VALUES ('4', '123456');

3. 5 operation results

4. End

This is where the simple interaction between unity3d and php comes from. In the actual development, we may use xml, json and other data formats to transfer data between unity and php. After mastering the above knowledge, these will become more simple, just like with the foundation, only need to add bricks and tiles, the house will become bigger and more beautiful.

Posted by subesc on Fri, 01 May 2020 17:04:34 -0700