3

Inside Unity I had prefabs, it calls "PropertyContainer" it filled with 2 text game object(Room_Type and Room_Qty) that I want to change it dynamically from my database. I had try to learn and watch any youtube tutorial and on the internet. After several weeks try searching and watching I still can't figure it out how to implementing into my code.

Below is my code that I got from several tutorial and some cases on the internet.
First code, is my php code that I used:

<?php
require 'Connection.php';

//Check Connection
if ($conn->connect_error){
    die("Connection Failed: " . $conn->connect_error);
}

//Create Variable Submitted
$ID_Type = 2;

$sql = "SELECT Room_Type, Room_Qty FROM House WHERE ID_Type = '" . $ID_Type . "'";
$result = $conn->query($sql);

if ($result->num_rows > 0){
    //Output data of each row.
    $rows = array();

    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    //After the whole array is created.
    echo json_encode($rows);
}else {
    echo "Zero Result";
}

$conn->close();?>

It calls GetStockHouse_RoseType.php, After it is successfully to show my value to be a Json file then the next step I need to call it into my Unity. There are several code that I'm used in unity.
Second code, using C# it called Web.cs:

public IEnumerator GetPropertyStock(string ID_Type, Action<string> callback)

{
    WWWForm form = new WWWForm();<br>
    form.AddField("ID_Type", ID_Type);

    using (UnityWebRequest www = UnityWebRequest.Get("http://localhost/xxxDB/GetStockHouse_RoseType.php"))
    {
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            //Show results as a text.
            Debug.Log(www.downloadHandler.text);
            string jsonArray = www.downloadHandler.text;

            callback(jsonArray);
        }
    }
}

Third code, called Items.cs:

Action<string> _createItemsCallback;
// Use this for initialization
void Start () {

    _createItemsCallback = (jsonArrayString) => {
        StartCoroutine(CreateItemsRoutine(jsonArrayString));
    };

    CreateItems();

}

// Update is called once per frame
public void CreateItems() {
    StartCoroutine(Main.Instance.Web.GetPropertyStock(_createItemsCallback));
}

IEnumerator CreateItemsRoutine(string jsonArrayString)
{
    //Parsing json array string as an array
    JSONArray jsonArray = JSON.Parse(jsonArrayString) as JSONArray;

    for (int i = 0; i < jsonArray.Count; i++)
    {
        //Create local variables
        bool isDone = false; //Are we done downloading?
        string ID_Type = jsonArray[i].AsObject["ID_Type"];
        JSONObject itemInfoJson = new JSONObject();

        //Create a callback to get the information from Web.cs
        Action<string> getItemInfoCallback = (itemInfo) =>
        {
            isDone = true;
            JSONArray tempArray = JSON.Parse(itemInfo) as JSONArray;
            itemInfoJson = tempArray[0].AsObject;
        };

        StartCoroutine(Main.Instance.Web.GetPropertyStock(ID_Type, getItemInfoCallback));

        //Wait until the callback is called from the Web (info finished downloading).
        yield return new WaitUntil(() => isDone == true);

        //Instantiate GameObject (item prefab).
        GameObject item = Instantiate(Resources.Load("Prefabs/PropertiContainer") as GameObject);
        item.transform.SetParent(this.transform);
        item.transform.localScale = Vector3.one;
        item.transform.localPosition = Vector3.zero;

        //Fill Information.
        item.transform.Find("Room_Type").GetComponent<Text>().text = itemInfoJson["Room_Type"];
        item.transform.Find("Room_Qty").GetComponent<Text>().text = itemInfoJson["Room_Qty"];
    }
    yield return null;
}

Fourth code, called Main.cs:

public static Main Instance;

public Web Web;

// Use this for initialization
void Start () {
    Instance = this;
    Web = GetComponent<Web>();
}

NOTES:
The second and the fourth code is set in into one(1) Empty Object on Unity while the third code is set in the parents that called PropertyContainer.

Bellow is the picture from my Unity: Picture No. 1) Main.cs & Web.cs set it into one Empty Object and also look oh my Game object for Room_Type and Room_Qty.

Main.cs & Web.cs

Main.cs & Web.cs

Item.cs

Item.cs

Unity File

Unity File

What I expected is two (2) text Game Objects (Room_Type and Room_Qty) on PropertyContainer can change into my .php code. I hope all that information can fully understand.

Maifee Ul Asad
  • 3,992
  • 6
  • 38
  • 86
Faj
  • 75
  • 9
  • What exactly is the problem? You have `WWWForm form = new WWWForm(); form.AddField("ID_Type", ID_Type);` but then you use a `Get` request without passing in the form data anywhere ... And did you know you can directly use `yield return Main.Instance.Web.GetPropertyStock(ID_Type, getItemInfoCallback);` that executes and waits for the routine to finish in one single line. – derHugo Jun 13 '19 at 13:21
  • Mind the SQL injection in the PHP code.. See [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Raymond Nijland Jun 13 '19 at 13:23
  • Also in the PHP you can best replace `else { echo "Zero Result"; }` with something like `else { json_encode(array('error', 'Zero Result')); }` As your C# code seams to be expecting valid json data. – Raymond Nijland Jun 13 '19 at 13:27
  • Also i would suggest adding `ini_set('display_errors', 1); error_reporting(E_ALL)` in the PHP code to enable ""debugging" mode to see if the PHP has errors. – Raymond Nijland Jun 13 '19 at 13:28
  • Hi All, the exactly problem is my 2 text game object did not replace as a string value as my database. – Faj Jun 13 '19 at 13:30
  • @RaymondNijland Hi, thx for your advise. I think I don't need to add that. Since this app will be used for personal not public but the place where this app used is on the public place. Kindly advise if this is need to be done? – Faj Jun 13 '19 at 13:39
  • @derHugo Hi, thx for answering my question. The truth is I still need to figure it out the code. Because what are you talking up there I didn't understand at all, I'm sorry it is the newbie mistake pls understand. For the sake of simplicity here's what I need to deal, I need those 2 text game objects change exactly like what I had in my database. What I had in my database is, ID, House_Type, and House_Qty. That my **PHP Code** is [{"Room_Type":"Melati_Room","Room_Qty":"6"}] after encoded with json. – Faj Jun 13 '19 at 13:45
  • 1
    and did you try to set breakpoints and debug where exactly the code is not acting as expected? Do you get the correct string from the database? do you receive the correct string in Unity? Is the parsing of the json working correctly? etc.... – derHugo Jun 13 '19 at 13:48
  • 1
    and actually you are trying to call `Main.Instance.Web.GetPropertyStock(_createItemsCallback)` but it requires a first parameter `ID_Type` – derHugo Jun 13 '19 at 13:50
  • @derHugo After I get rid of the Items.cs and I tried to startcoroutine the Ienumerators on the Web.cs It works. It showed like this "[{"Room_Type":"Rose_Room","Room_Qty":"6"}] UnityEngine.Debug:Log(Object) c__Iterator0:MoveNext() (at Assets/Web.cs:31) UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)" – Faj Jun 13 '19 at 13:56
  • @derHugo I think the next step is to put the string on the game object, but Idk how to, pls help. – Faj Jun 13 '19 at 14:00

0 Answers0