簡體   English   中英

使用C#調用php腳本(Unity)

[英]Calling php script using C# (Unity)

我對Unity和PHP都很陌生,我目前正在開發一個項目,我可以使用PHP將MySQL數據庫中的數據解析為Unity。

我最初想嘗試啟用一種方法,用戶可以更改php腳本並使其能夠選擇不同的數據表,但我被告知,在php腳本中列出所有變量並從中調用它可能更安全相應的統一;

Display.php的

$table = mysql_real_escape_string($_GET['table'], $db);

if ($table == "shoes") { 
    $query = "SELECT * FROM `shoes` ORDER by `price` ASC LIMIT 10";

elseif ($table == "sneakers") { 
    $query = "SELECT * FROM `sneakers` ORDER by `price` ASC LIMIT 10";

$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$num_results = mysql_num_rows($result);  

for($i = 0; $i < $num_results; $i++)
{
    $row = mysql_fetch_array($result);
    echo $row['shopname'] . "\t" . $row['price'] . "\n";
}

我在調用php並選擇我想要選擇的表時遇到了麻煩,我對此很新,所以如果這對你們來說似乎完全無能,我會道歉。

這是我的Unity腳本;

HSController.cs

void Start()
{
    StartCoroutine(GetScores());
}

// remember to use StartCoroutine when calling this function!
IEnumerator PostScores(string name, int score)
{

    string hash = Md5Sum(name + score + secretKey);

    string post_url = addScoreURL + "name=" + WWW.EscapeURL(name) + "&score=" + score + "&hash=" + hash;

    WWW hs_post = new WWW(post_url);
    yield return hs_post; // Wait until the download is done

    if (hs_post.error != null)
    {
        print("There was an error posting the high score: " + hs_post.error);
    }
}

IEnumerator GetScores()
{
    gameObject.guiText.text = "Loading...";
    WWW hs_get = new WWW(highscoreURL);
    yield return hs_get;

    if (hs_get.error != null)
    {
        print("There was an error getting the high score: " + hs_get.error);
    }
    else
    {
        gameObject.guiText.text = hs_get.text; // this is a GUIText that will display the scores in game.
    }
}

任何幫助或正確方向上的一點都會很棒!

親切的問候

讓我嘗試將其重寫為一個工作示例:

C#

void Start() {
    StartCoroutine(GetData());
}


IEnumerator GetData() {
    gameObject.guiText.text = "Loading...";
    WWW www = new WWW("http://yoururl.com/yourphp.php?table=shoes"); //GET data is sent via the URL

    while(!www.isDone && string.IsNullOrEmpty(www.error)) {
        gameObject.guiText.text = "Loading... " + www.Progress.ToString("0%"); //Show progress
        yield return null;
    }

    if(string.IsNullOrEmpty(www.error)) gameObject.guiText.text = www.text;
    else Debug.LogWarning(www.error);
}

PHP

<?php

//DB connection goes here

if ($_REQUEST['table'] === "shoes") { //I'm using REQUEST instead of GET, so it will work with both GET and POST
    $query = "SELECT * FROM `shoes` ORDER by `price` ASC LIMIT 10";
} elseif ($_REQUEST['table'] === "sneakers") { 
    $query = "SELECT * FROM `sneakers` ORDER by `price` ASC LIMIT 10";
}

$result = mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_assoc($result)) {
    echo  $row['shopname'] . "\t" . $row['price'] . "\n"; 
}
?>

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM