1

So I have this application in Unity that I am making and I am trying to connect it to a mySQL database that I made and connected to a website. I am able to insert things through a form on the website into the database. That is working.

What I want to do next is connect the Unity app so that it can also access the things in the database. I am coding in C# and php. I want the unity application to ask the website for certain information from the database. The website should then look in the database and return some info to the unity application.

THIS IS NOT A DUPLICATE question. I have looked at the questions on here and I still can't get it to work. Right now my unity application is able to send a message to my webpage which my webpage then echos properly. (I know this isn't the functionality I talked about but I am just testing right now). However when I then go try to get my response in my Unity application from my webpage, all I debug is <html>.

You can access my website at: http://historicstructures.org/forms.html

Here is my php code:

<html> 

<style type="text/css">
    body {background-color:#666666; color: white;}
</style> 
<body>
<h1 align = "center">
<img src="housebackground.jpg" alt="Mountain View" style="width:97%;height:228px;" ></h1>
<h1 align = "center">Submission Status</h1>
<p align = "center">
<?php


//this is the variable that is being recieved from the unity script
$AuthorName = $_POST["Author"];

//here i am printing it out so that it will be sent back to the unity script 
    // i am also echoing it onto the webpage so that i know it is getting the variable 
    //correctly from the unity script
echo $AuthorName;
header("Access-Control-Allow-Origin: *");
print($AuthorName);

//gets all the variables the user inputted to form
$StructureName = $_POST["StructureName"];
$Author = $_POST["Author"];
$YearBuilt = $_POST["YearBuilt"];
$EraBuilt = $_POST["EraBuilt"];
$YearDestroyed = $_POST["YearDestroyed"];
$EraDestroyed = $_POST["EraDestroyed"];
$Latitude = $_POST["Latitude"];
$Longitude = $_POST["Longitude"];
$Structurelink = "no exist yet";

//checks to make sure the information is in the right format
$isValid = true; 
$errCode = 0; 

if ($Latitude<-90 || $Latitude>90){
    $isValid = false;
    $errCode = 1; 

}

if ($Longitude<-180 || $Longitude>180){
    $isValid = false;
    $errCode = 2; 

}

if ($YearBuilt<-400 || $YearBuilt>400){
    $isValid = false;
    $errCode = 3; 

}

 if ($YearDestroyed<-400 || $YearDestroyed>400){
    $isValid = false;
     $errCode = 4; 

}



//if the informationt the user gave was correct, then insert into database
if ($isValid ==true){

    $servername = "localhost";
    $username = "...";
    $password = "...";
    $dbname = "StructureInfo";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 


    $sql = "INSERT INTO info (ID, StructureName, Author, YearBuilt, EraBuilt, YearDestroyed, EraDestroyed, Latitude, Longitude, StructureLink)
    VALUES ('null','$StructureName','$Author','$YearBuilt','$EraBuilt','$YearDestroyed','$EraDestroyed','$Latitude','$Longitude','$Structurelink')";

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }


    $conn->close(); 

}


//the user has an error in the information they inputted 
else{
    echo "Your submission was invalid and so it was not submitted. ";

    switch ($errCode) {
    case 1:
        echo "Your latitude is out of bounds.";
        break;
    case 2:
        echo "Your longitude is out of bounds. ";
        break;
    case 3:
        echo "Your year built is out of bounds. ";
        break;
    case 4:
        echo "Your year destroyed is out of bounds. ";
        break;
    default:
        echo "Go back and review your data to make sure it is correct.";
    }
}

?>
</p>

<br><br>
</body>
</html>

Here is my unity code which is attached to a button, I wasn't sure where to put it so my onclick for the button is the main of this js:

#pragma strict

function Start () {

}

function Update () {

}

function GetFromDB(){
     var url = "http://historicstructures.org/action_page_post.php";
     var form = new WWWForm();
     form.AddField( "Author", "Jess" );

     var www = new WWW( url, form );

     // wait for request to complete
     yield www;

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

GetFromDB();
Programmer
  • 121,791
  • 22
  • 236
  • 328
  • 1
    Possible duplicate of [Accessing MySQL database using c# on unity?](https://stackoverflow.com/questions/17029389/accessing-mysql-database-using-c-sharp-on-unity) – Tiago Martins Peres Oct 03 '19 at 10:47

1 Answers1

1

First of all, your code is Javascript/Unityscript but you tagged C#. I think that you should be using C# as it has more features and support than Javascript/Unityscript.

Here is my unity code which is attached to a button, I wasn't sure where to put it so my onclick for the button is the main of this js

Create a C# script then subscribe to the Button's onClick event. When the Button is pressed, Start coroutine that will connect to your database.

public Button button;

void OnEnable()
{
    button.onClick.AddListener(() => { StartCoroutine(GetFromDB()); });
}

void OnDisable()
{
    button.onClick.RemoveAllListeners();
}

IEnumerator GetFromDB()
{
    var url = "http://historicstructures.org/action_page_post.php";
    var form = new WWWForm();
    form.AddField("Author", "Jess");

    WWW www = new WWW(url, form);

    // wait for request to complete
    yield return www;

    // and check for errors
    if (String.IsNullOrEmpty(www.error))
    {
        UnityEngine.Debug.Log(www.text);
    }
    else
    {
        // something wrong!
        UnityEngine.Debug.Log("WWW Error: " + www.error);
    }
}

If you are new to C#, this Unity tutorial should get you started. You can find other Unity UI event samples here.

EDIT:

However when I then go try to get my response in my Unity application from my webpage, all I debug is <html>.

I didn't see the <html> in your original question. That's because <html> can be used on stackoverflow to arrange text. I edited your question and formatted the <html> into a code to make it show up.

There is nothing wrong with your code. Unity simply did not display all other data received from the server because there is a new line in your code. Simply click on the <html> log you see in the Editor and it show you all the other data from the server. You must click on that error in the Editor to see the rest of the data.

Note that your current script will output error to Unity:

Your submission was invalid and so it was not submitted.

That's because you did not fill all the forms required.

This should do it:

form.AddField("Author", "Jess");
form.AddField("YearDestroyed", "300");
form.AddField("YearBuilt", "300");
form.AddField("Longitude", "170");
form.AddField("Latitude", "60");
form.AddField("StructureName", "IDK");

Few more things:

1.Remove the html code from your server. That should not be there if you want to use POST/GET. It will be hard to extract your data if you have the html code there. So, your code should only start from <?php and end with ?>

2.If you are going to receive more than 1 data from the server, use json.

On the PHP side, use json_encode to convert your data to json the send to Unity with print or echo. Google json_encode for more information.

On Unity C# side, use JsonUtility or JsonHelper from this post to deserialize the data from the server.

3.Finally, instead of building the error message and outputting to Unity from the server, simply send the error code from the server.

On Unity C# side, make a class that converts the error code into full error message.

Community
  • 1
  • 1
Programmer
  • 121,791
  • 22
  • 236
  • 328
  • Thank you for your reply!! Sorry about the C# mix up . My entire app is in C# but I found a tutorial in JS which is why i used it. Ok so I am still having the same problem where the webpage is getting the message but the return message from the website is still not getting back to my unity application. Is there something wrong with my code using the wwwforms? I also tried transitioning from using a button to just running function GetFromDB() on the start of the application because eventually I will just be calling it when I need something from the db. – Jessica Napolitano Apr 14 '17 at 14:54
  • Can you edit your question and update it with your complete php script. Also, can you provide me the url you are using to do this? I want to try it my self and see what happens. Finally, can you access that url from the web browser? If you can't you will probably not be able to from Unity. – Programmer Apr 14 '17 at 18:13
  • Ok I just edited the php script so that it is complete. The only part that is talking to the unity script is at the top as indicated in the comments. I also added the url to the questions above. Yes it is accessible from a web browser. I am hosting it at godaddy. In addition, I realized that it is prone to an sql attack. I will address that soon. haha I am just trying to get it to work right now. – Jessica Napolitano Apr 18 '17 at 00:03
  • Check the Edit I made in my answer. – Programmer Apr 18 '17 at 06:20
  • Thank you so so much!!! I just tried sending a variable from my unity script to the php script and then back and it worked!! Wow thank you for your patience. Just a quick question is the json necessary? Why wouldn't it work if I just echoed the information from the php script and seperated them by commas and then just parse it in unity? – Jessica Napolitano Apr 21 '17 at 17:51
  • json is **not** necessary. You can also use xml. Also, you can construct the information and separate the data with commas, then send it to Unity like you said. That should work too. The idea of using comma is really old. That's should be used only when json is not available on that platform. Example is when doing embedded programming with Arduino but this is not the case here. – Programmer Apr 22 '17 at 03:57
  • You should use json instead of commas as it is easier to troubleshoot your data. Every web API is either using json or xml. Ask yourself what happens when you use commas then the data actually contains a real comma, the order you read your data will no longer match. You won't have this problem with json or xml. – Programmer Apr 22 '17 at 04:00
  • Don't forget to accept answers if your problem is solved. I noticed you haven't done so in the past and you probably didn't know you could. There is a difference between up-voting and accepting answers. See [here](https://meta.stackexchange.com/a/5235) for how to accept answers. You can always ask new questions if you have one. – Programmer Apr 22 '17 at 04:02
  • Ok that makes a lot of sense with respect to the json. And wow I thought I had to click the up vote to accept and it always said I didn't have enough points so I couldn't. I had no idea that's how you accepted an answer. haha well thank you!! I really appreciate all your help. I just accepted it – Jessica Napolitano Apr 24 '17 at 12:43
  • That's fine. You can also upvote and accept answer at the-same time. Upvote = the answer is useful. Accept = this answer solved my problem. Happy coding! – Programmer Apr 24 '17 at 12:47