Unity -連線 php 與 MySQL 資料庫

這篇文章將介紹如何讓 unity 連線 php 網頁,再透過 php 網頁去取得資料庫的資料。

環境
Unity Unity 2021.3.10f1 (64-bit)
遠端主機 cloudways
MariaDB 10.4
php 7.4

工作時常常會遇到處理多國語言的情況,所以每次遇到字串處理,我一定會用日文去測試 unicode 或 utf-8,用中文不準。

1. 連線 php 網頁-傳遞簡單字串和數字參數並回傳

php 程式碼 – unitytest0202.php

<?php
	$userName = $_GET["name"];
	$id = $_GET["id"];
			
	echo $userName.$userName."</next>".$id;
?>

unity 程式碼 – WebPhp.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Text.RegularExpressions;

public class WebPhp : MonoBehaviour
{
    void Start()
    {
        ConnectToPhp01();
    }
	public void ConnectToPhp01()
    {
        StartCoroutine(Test01());
    }
    IEnumerator Test01()
    {
        string strName = "Harry";
        int id = 1;

        string strUrl = string.Format("http://localhost/unitytest0202.php?name={0}&id={1}",
                         strName, id);

        UnityWebRequest request = UnityWebRequest.Get(strUrl);

        yield return request.SendWebRequest();

        if (request.result == UnityWebRequest.Result.ConnectionError)
        {
            Debug.Log(request.error);
            yield break;
        }

        string html = request.downloadHandler.text;
        Debug.Log(html);
    }
}

執行結果

2. 連線 php 網頁-傳遞 utf-8 日文字串

unity 編輯器預設產生出來的 C# script 檔案是 utf-8 的
所以日文字可以直接放進去存檔

unity 程式碼 – WebPhp.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Text.RegularExpressions;

public class WebPhp : MonoBehaviour
{
	void Start()
	{
		ConnectToPhp03();
	}
	public void ConnectToPhp03()
	{
		StartCoroutine(Test03());
	}
	IEnumerator Test03()
	{
		string strName = "ハリー";
		int id = 3;

		string strUrl = string.Format("http://localhost/unitytest0202.php?name={0}&id={1}",
			strName, id);

		UnityWebRequest request = UnityWebRequest.Get(strUrl);
		yield return request.SendWebRequest();

		if (request.result == UnityWebRequest.Result.ConnectionError)
		{
			Debug.Log(request.error);
			yield break;
		}

		string html = request.downloadHandler.text;
		Debug.Log(html);
    }
}

執行結果

3. 連線 php 網頁-取得 MySQL 資料庫資料

建立 MySQL 資料表

-- ----------------------------
-- Table structure for test01
-- ----------------------------
DROP TABLE IF EXISTS `test01`;
CREATE TABLE `test01`  (
  `id` int(11) NOT NULL,
  `int_test` int(11) NOT NULL,
  `char_test` char(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `varchar_test` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `text_test` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of test01
-- ----------------------------
INSERT INTO `test01` VALUES (1, 10, 'a', 'Harry Potter', 'The novels chronicle the lives of a young wizard, Harry Potter, whom are students at Hogwarts School of Witchcraft and Wizardry.');
INSERT INTO `test01` VALUES (2, 20, 'b', '哈利波特', '是一部兒童奇幻文學系列小說,描寫主角哈利波特在霍格華茲魔法學校7年學習生活中的冒險故事。');
INSERT INTO `test01` VALUES (3, 30, 'c', 'ハリー・ポッター', '1990年代のイギリスを舞台に、魔法使いの少年ハリー・ポッターの学校生活。');

SET FOREIGN_KEY_CHECKS = 1;

php 程式碼 – unitytest0101.php

<?php
	// 建立MySQL的資料庫連接 
	$host = "localhost";
	$dbuser = "user";
	$dbpassword = "password";
	$dbname = "database";
	
	$link = mysqli_connect($host,$dbuser,$dbpassword,$dbname);
	if ( !$link ) 
	{
		echo "不正確連接資料庫 " . mysqli_connect_error();
		echo "<br>";
		exit();
	}
	
	mysqli_query($link, "SET NAMES utf8");
	mysqli_query($link, "SET CHARACTER_SET_database= utf8");
	mysqli_query($link, "SET CHARACTER_SET_CLIENT= utf8");
	mysqli_query($link, "SET CHARACTER_SET_RESULTS= utf8");

	$sql = "select * from test01";
	
	$result = mysqli_query($link, $sql);
	
	if (!$result) 
	{
		echo "{$sql} 語法執行失敗,錯誤訊息 " . mysqli_error($link);
		echo "<br>";
		mysqli_close($link);  // 關閉資料庫連接
		exit();
	}
	
	$rowNum = mysqli_num_rows($result);
	if ($rowNum <= 0)
	{
		echo "沒有資料";
		echo "<br>";
		mysqli_close($link);  // 關閉資料庫連接
		exit();
	}
	
	while($array = mysqli_fetch_array($result))
	{
		echo $array["int_test"]."</next>";
		echo $array["varchar_test"]."</next>";
	}
	
	mysqli_free_result($result);
	
	mysqli_close($link);  // 關閉資料庫連接
	
?>

unity 程式碼 – WebPhp.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Text.RegularExpressions;

public class WebPhp : MonoBehaviour
{
	void Start()
	{
		ConnectToPhp02();
	}
	public void ConnectToPhp02()
	{
		StartCoroutine(Test02());
	}
	IEnumerator Test02()
	{
		string strUrl = "http://localhost/unitytest0101.php";

		UnityWebRequest request = UnityWebRequest.Get(strUrl);
		yield return request.SendWebRequest();

		if (request.result == UnityWebRequest.Result.ConnectionError)
		{
			Debug.Log(request.error);
			yield break;
		}

		string html = request.downloadHandler.text;
		Debug.Log(html);

		var received_data = Regex.Split(html, "</next>");
		int dataNum = (received_data.Length - 1) / 2;

		Debug.Log("dataNum = " + dataNum.ToString());

		for (int i = 0; i < dataNum; i++)
		{
			Debug.Log("Number: " + received_data[2 * i] + " Name: " + received_data[2 * i + 1]);
		}
    }
}

執行結果

參考網址
https://blog.csdn.net/mseol/article/details/69061178

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *