2016年10月29日 星期六

[Unity 3D] 透過php檔案存取MySql資料庫

網頁部分
安裝架站伺服器XAMPP (https://www.apachefriends.org/zh_tw/index.html)
安裝完成後,找到在此路徑下C:\xampp\htdocs放要執行SQL語法的網頁,如下:此範例圖示.php的檔案內容,內容是新增一筆資料到MySQL資料庫,完成後將檔案儲存在C:\xampp\htdocs底下



Unity 部分
讀取資料
using UnityEngine;
using System.Collections;
using System.IO;
using System.Net;
using UnityEngine.UI;

public class rankingboard : MonoBehaviour
{
    public string url;  //url是指要連結的php檔案位置,此範例為127.0.0.1/select.php
    HttpWebRequest request;

    void Update()
    { 
 StartCoroutine (reflashboard ());
    }

    IEnumerator reflashboard()
    {
 yield return new WaitForSeconds (2f);
 request = (HttpWebRequest)WebRequest.Create(url);
 //request.Method = "POST";
 request.ContentType = "application/x-www-form-urlencoded";
 
 WebResponse response = request.GetResponse();
 Stream stream = response.GetResponseStream();

 StreamReader sr = new StreamReader(stream);

 rankinginfo = sr.ReadToEnd();
 string[] word = rankinginfo.Trim().Split(',');

 //word[0]就是讀到的第一筆資料 
    }
}
新增,刪除,修改資料(要執行那一個功能,是根據連結到的php檔案是執行刪除的sql語法還是刪除或修改的sql語法)
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.Net;

public class ButtonClick : MonoBehaviour {
{
    public string url;  //url是指要連結的php檔案位置,此範例為127.0.0.1/insert.php

    void Update()
    { 
 WWWForm form = new WWWForm ();
 form.AddField ("score", score.ToString ());    //score是php檔案內的$_POST['score'],單引號內的變數
 form.AddField ("groups", team_name);           //groups是$_POST['groups'],單引號內的變數
        for (int i = 0; i < DBcolumn.Length; i++)
 {
     form.AddField (DBcolumn[i], inputfield[i].text);
 }
 WWW www = new WWW (url, form);
 StartCoroutine (updatesco (www));
    }

    IEnumerator (updatesco (WWW www){
 yield return www;
    }
}
沒有範例

沒有留言: