Unity x Mysql x PHP x Json

2022/12/18閱讀時間約 25 分鐘
開啟Xampp伺服器,並啟動 apache & mysql

mysql建立

開啟Unity 建立 Script

toPhp.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; //UI物件需要增加此行
using UnityEngine.Networking;
using System.Text.RegularExpressions;
public class toPhp : MonoBehaviour
{
    public Text UItext; //要設公開的才能從外部加入UItext
    public Text MYtext;
    // Start is called before the first frame update
    void Start()
    {
    }
    public void ConnectTophp()
    {
        StartCoroutine(Test());
    }
    IEnumerator Test()
    {
        string strText = "hello";
        string strUrl = string.Format("http://localhost/unitymysql/test.php?a={0}", strText);
        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;
        changeUItext(html);
        Debug.Log(html);
    }
    public void changeUItext(string html)
    { //設公開的才能利用Unity內建Button觸發方式來喚出
        UItext.text = html;
    }
    // Update is called once per frame
    void Update()
    {
        
    }
    public void ConnectMysql()
    {
        StartCoroutine(Testdb());
    }
    IEnumerator Testdb()
    {
        string strUrl = "http://localhost/unitymysql/connectmysql.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++)
        {
            string myhtml = "Name: " + received_data[2 * i] + " email: " + received_data[2 * i + 1];
            changeMYtext(myhtml);
            Debug.Log("Name: " + received_data[2 * i] + " email: " + received_data[2 * i + 1]);
        }
    }
    public void changeMYtext(string myhtml)
    { //設公開的才能利用Unity內建Button觸發方式來喚出
        MYtext.text = myhtml;
    }
}

Unity物件

toWeb物件設定

此處需特別留意設定 UItext & MYtext ,否則會出現物件未設定的Null錯誤

Button 設定

測試連線按鈕
連結mysql按鈕

test.php

<?php
	$a = $_GET["a"];
			
	echo $a;
?>

connectmysql.php

<?php
	// 建立MySQL的資料庫連接 
	$host = "localhost";
	$dbuser = "root";
	$dbpassword = "1234";
	$dbname = "user";
	
	$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 users";
	
	$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["name"]."</next>";
		echo $array["email"]."</next>";
	}
	
	mysqli_free_result($result);
	
	mysqli_close($link);  // 關閉資料庫連接
	
?>

使用 Json

使用 Json 傳輸的 toPhp.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; //UI物件需要增加此行
using UnityEngine.Networking;
using System.Text.RegularExpressions;
public class toPhp : MonoBehaviour
{
    public Text UItext; //要設公開的才能從外部加入UItext
    public Text MYtext;
    public Text Stext; //Json 用
    public Text Utext; //Json 用
    public string Selectx = "http://localhost/unitymysql/tojsonsel.php";
    public string Updatex = "http://localhost/unitymysql/tojsonup.php";
    // Start is called before the first frame update
    void Start()
    {
    }
    public void ConnectTophp()
    {
        StartCoroutine(Test());
    }
    IEnumerator Test()
    {
        string strText = "hello";
        string strUrl = string.Format("http://localhost/unitymysql/test.php?a={0}", strText);
        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;
        changeUItext(html);
        Debug.Log(html);
    }
    public void changeUItext(string html)
    { //設公開的才能利用Unity內建Button觸發方式來喚出
        UItext.text = html;
    }
    // Update is called once per frame
    void Update()
    {
        
    }
    public void ConnectMysql()
    {
        StartCoroutine(Testdb());
    }
    IEnumerator Testdb()
    {
        string strUrl = "http://localhost/unitymysql/connectmysql.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++)
        {
            string myhtml = "Name: " + received_data[2 * i] + " email: " + received_data[2 * i + 1];
            changeMYtext(myhtml);
            Debug.Log("Name: " + received_data[2 * i] + " email: " + received_data[2 * i + 1]);
        }
    }
    public void changeMYtext(string myhtml)
    { //設公開的才能利用Unity內建Button觸發方式來喚出
        MYtext.text = myhtml;
    }
    //json
    public void JsonSelect()
    { //設公開的才能利用Unity內建Button觸發方式來喚出
        StartCoroutine(SelectJson());
    }
    IEnumerator SelectJson()
    {
        WWWForm form = new WWWForm();
        form.AddField("getlist", "all");
        using (UnityWebRequest www = UnityWebRequest.Post(Selectx, form))
        {
        www.downloadHandler = new DownloadHandlerBuffer();
        yield return www.SendWebRequest();
        if (www.result == UnityWebRequest.Result.ConnectionError)
            {
                Debug.Log(www.error);
            }
            else
            {
                string responseText = www.downloadHandler.text;
                Stext.text = responseText;
                Debug.Log(responseText);
            }
        }
    }
    public void JsonUpdate()
    { //設公開的才能利用Unity內建Button觸發方式來喚出
        StartCoroutine(UpdateJson());
    }
    IEnumerator UpdateJson()
    {
        WWWForm form = new WWWForm();
        form.AddField("udata", "'abc'");
        form.AddField("edata", "'abc'");
        using (UnityWebRequest www = UnityWebRequest.Post(Updatex, form))
        {
            www.downloadHandler = new DownloadHandlerBuffer();
            yield return www.SendWebRequest();
            if (www.result == UnityWebRequest.Result.ConnectionError)
            {
                Debug.Log(www.error);
            }
            else
            {
                string responseText = www.downloadHandler.text;
                Utext.text = responseText;
                Debug.Log(responseText);
            }
        }
    }
    }

tojsonsel.php

<?php
	// 建立MySQL的資料庫連接 
	$host = "localhost";
	$dbuser = "root";
	$dbpassword = "1234";
	$dbname = "user";
	
	$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 users";
	
	$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();
	}
	
	$ary[]= array();
	while($row = mysqli_fetch_assoc($result))
	{
		$ary=$row;
	}
	echo json_encode($ary);
	
	mysqli_free_result($result);
	
	mysqli_close($link);  // 關閉資料庫連接
	
?>

tojsonup.php

<?php
	$udata=$_POST["udata"];
	$edata=$_POST["edata"];
	// 建立MySQL的資料庫連接 
	$host = "localhost";
	$dbuser = "root";
	$dbpassword = "1234";
	$dbname = "user";
	
	$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");
//$udata='51';
	mysqli_select_db($link,"user");
	$sql = "update users set name ={$udata},email ={$edata} where id ='51'";
	
	$result = mysqli_query($link, $sql);
	
	if (!$result) 
	{
		echo "{$sql} 語法執行失敗,錯誤訊息 " . mysqli_error($link);
		echo "<br>";
		mysqli_close($link);  // 關閉資料庫連接
		exit();
	}
	
	mysqli_free_result($result);
	
	mysqli_close($link);  // 關閉資料庫連接
	
?>
為什麼會看到廣告
38會員
129內容數
獨立遊戲開發紀錄
留言0
查看全部
發表第一個留言支持創作者!