微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用C#调用php脚本(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"; 
}
?>

希望这可以帮助!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐