Unity x Mysql x PHP x Json

更新於 發佈於 閱讀時間約 24 分鐘
raw-image

開啟Xampp伺服器,並啟動 apache & mysql

raw-image

mysql建立

raw-image

開啟Unity 建立 Script

raw-image

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物件

raw-image

toWeb物件設定

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

Button 設定

raw-image
raw-image

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); // 關閉資料庫連接

?>
留言
avatar-img
留言分享你的想法!
avatar-img
MJ的沙龍
42會員
136內容數
獨立遊戲開發紀錄
MJ的沙龍的其他內容
2025/04/12
🗓 Steam 上市日期:2025/4/28 | 🖤 加入願望清單:https://store.steampowered.com/app/3634400/Elara/ 「他們說我太敏感,說我不合群。 但我只是——不想學會沉默。」 —Elara Quinn 你是否曾經在工作時,感
Thumbnail
2025/04/12
🗓 Steam 上市日期:2025/4/28 | 🖤 加入願望清單:https://store.steampowered.com/app/3634400/Elara/ 「他們說我太敏感,說我不合群。 但我只是——不想學會沉默。」 —Elara Quinn 你是否曾經在工作時,感
Thumbnail
2025/03/05
在靈異頻發的醫院夜班,小護士林筱筱意外發現她的冷酷上司——蘇醫生,竟然早已死亡五年,從此她與這位神秘的「鬼醫生」攜手處理靈異事件,並在驚魂不斷的夜班中逐漸建立起一段超越生死的羈絆。
Thumbnail
2025/03/05
在靈異頻發的醫院夜班,小護士林筱筱意外發現她的冷酷上司——蘇醫生,竟然早已死亡五年,從此她與這位神秘的「鬼醫生」攜手處理靈異事件,並在驚魂不斷的夜班中逐漸建立起一段超越生死的羈絆。
Thumbnail
2025/02/24
這是一篇懸疑驚悚小說,描述女主角江語珊調查一起離奇命案的故事。死者林曦是一位心理學教授,死於自家公寓,現場佈滿鏡子,死者嘴角帶著詭異的微笑。語珊在調查過程中發現,此案與一種名為「鏡像侵蝕」的心理現象有關,並逐漸被捲入其中。
Thumbnail
2025/02/24
這是一篇懸疑驚悚小說,描述女主角江語珊調查一起離奇命案的故事。死者林曦是一位心理學教授,死於自家公寓,現場佈滿鏡子,死者嘴角帶著詭異的微笑。語珊在調查過程中發現,此案與一種名為「鏡像侵蝕」的心理現象有關,並逐漸被捲入其中。
Thumbnail
看更多
你可能也想看
Thumbnail
創作者營運專員/經理(Operations Specialist/Manager)將負責對平台成長及收入至關重要的 Partnership 夥伴創作者開發及營運。你將發揮對知識與內容變現、影響力變現的精準判斷力,找到你心中的潛力新星或有聲量的中大型創作者加入 vocus。
Thumbnail
創作者營運專員/經理(Operations Specialist/Manager)將負責對平台成長及收入至關重要的 Partnership 夥伴創作者開發及營運。你將發揮對知識與內容變現、影響力變現的精準判斷力,找到你心中的潛力新星或有聲量的中大型創作者加入 vocus。
Thumbnail
本文將介紹在Windows環境中安裝Oracle Instant Client及相關PHP擴展,以進行與Oracle Database的串接。透過本文所述步驟,您將能在Windows環境中順利進行PHP與Oracle Database的串接設定。
Thumbnail
本文將介紹在Windows環境中安裝Oracle Instant Client及相關PHP擴展,以進行與Oracle Database的串接。透過本文所述步驟,您將能在Windows環境中順利進行PHP與Oracle Database的串接設定。
Thumbnail
php.ini 1.short_open_tag = On 2.register_globals = Off 3.display_errors = On 4.error_reporting = E_ALL & ~E_NOTICE 5.date.timezone = Asia/Tai
Thumbnail
php.ini 1.short_open_tag = On 2.register_globals = Off 3.display_errors = On 4.error_reporting = E_ALL & ~E_NOTICE 5.date.timezone = Asia/Tai
Thumbnail
在欄位輸入關鍵字,就會顯示提示列表。 架構 由HTML表單、jQuery的AJAX和PHP與MySQL組成。 先在HTML的文字輸入欄位,輸入關鍵字,接著會呼叫jQuery的AJAX去伺服器,取得建議列表;伺服器收到需求後,PHP會連接MySQL,取得建議列表,接著會建立JSON文件並回傳。
Thumbnail
在欄位輸入關鍵字,就會顯示提示列表。 架構 由HTML表單、jQuery的AJAX和PHP與MySQL組成。 先在HTML的文字輸入欄位,輸入關鍵字,接著會呼叫jQuery的AJAX去伺服器,取得建議列表;伺服器收到需求後,PHP會連接MySQL,取得建議列表,接著會建立JSON文件並回傳。
Thumbnail
底下是HTML的上傳檔案程式碼: <form action="upload.php" method="post" enctype="multipart/form-data"> 選擇檔案: <input type="file" name="file"/><hr/> <input typ
Thumbnail
底下是HTML的上傳檔案程式碼: <form action="upload.php" method="post" enctype="multipart/form-data"> 選擇檔案: <input type="file" name="file"/><hr/> <input typ
Thumbnail
承上篇,繼續往下走吧! 來說明一下 PHP 兩個會用到的套件安裝,一個是 ionCube,另一個為 memcached ●PHP 套件 ionCube 安裝 先以下列指令,在帳戶內建立一個 tmp 資料夾備用,執行時留意是在帳號剛登入主機的位置喔!
Thumbnail
承上篇,繼續往下走吧! 來說明一下 PHP 兩個會用到的套件安裝,一個是 ionCube,另一個為 memcached ●PHP 套件 ionCube 安裝 先以下列指令,在帳戶內建立一個 tmp 資料夾備用,執行時留意是在帳號剛登入主機的位置喔!
Thumbnail
開啟Xampp伺服器,並啟動 apache & mysql mysql建立 開啟Unity 建立 Script toPhp.cs Unity物件 toWeb物件設定 此處需特別留意設定 UItext & MYtext ,否則會出現物件未設定的Null錯誤 Button 設定 test.php con
Thumbnail
開啟Xampp伺服器,並啟動 apache & mysql mysql建立 開啟Unity 建立 Script toPhp.cs Unity物件 toWeb物件設定 此處需特別留意設定 UItext & MYtext ,否則會出現物件未設定的Null錯誤 Button 設定 test.php con
Thumbnail
假設資料如下: local DB裡面的test Collection SELECT SELECT可以這樣寫: 由於config/database.php中設定的default DB_CONNECTION是mysql,所以這邊特別指定使用mongodb connection。 回傳結果如下: 軟刪除
Thumbnail
假設資料如下: local DB裡面的test Collection SELECT SELECT可以這樣寫: 由於config/database.php中設定的default DB_CONNECTION是mysql,所以這邊特別指定使用mongodb connection。 回傳結果如下: 軟刪除
追蹤感興趣的內容從 Google News 追蹤更多 vocus 的最新精選內容追蹤 Google News