Blar321 Blar321 - 4 months ago 17
PHP Question

How do I access a database in Unity?

I am trying to POST data to my database in Unity and it doesn't seem to be working. I know it is probably a very stupid mistake as I do have little knowledge in this field.

The C# script I have:



void logIn(string test) {
WWWForm form = new WWWForm();
form.AddField("action","send");
form.AddField("var1",test);
string url = "http://www.prizechief.com/unitycon.php";
WWW w = new WWW(url, form);

}

void Start() {
string sample = "Works";
logIn(sample);


}





My PHP code



<?php
$con = @mysqli_connect("server","un","pass", "db") or die("Could not connect " . mysqli_connect_error() . "Please try again later.");

$var1 = $_GET['var1'];
echo $var1;

mysqli_Query($con,"INSERT INTO test (var) VALUE ('$var1')");
?>





Also, a hint on how to use GET to receive information would be greatly appreciated!


Answer

Try this. That should do the WWW request and set $_GET['var1'] = to value1 in your PHP script. Now of course you will have to change that to your variable down the road. But just to test for now. If this doesn't work let me know what the debug logs print out.

void Start () {
    string url = "http://www.prizechief.com/unitycon.php?var1=value1";
    WWW www = new WWW(url);
    StartCoroutine(WaitForRequest(www));
}

IEnumerator WaitForRequest(WWW www)
{
    yield return www;

    // check for errors
    if (www.error == null)
    {
        Debug.Log("WWW Ok!: " + www.data);
    } else {
        Debug.Log("WWW Error: "+ www.error);
    }    
}

EDIT

Remember to go into Edit > Player Settings > Editor and change the URL to your domain.