2

I've been saving data in this HashSet of strings and i want to send that HashSet to a php file (web service).this is just an exemple of what am trying to do. in the app am working on the list's length which is about 20.

My question is, is there a way to pass a list to a WWWForm ? if not is there any other way?

string CreateUserURL = "localhost:81/ARFUR/InsertUser.php";
// Use this for initialization
void Start () {
    HashSet<string> list = new HashSet<string>();
}

// Update is called once per frame
void Update () {
    if(Input.GetKeyDown(KeyCode.Space)) CreateUser(inputUserName, inputPassword);
}

public void CreateUser(string username, string password){
    WWWForm form = new WWWForm();
    list.Add(username);
    list.Add(password);
    // What I want to do 
    form.AddField("list", list);
    WWW www = new WWW(CreateUserURL, form);

}
Neuron
  • 5,141
  • 5
  • 38
  • 59
Med yacine
  • 53
  • 6

1 Answers1

1

First, note that HashSet<string> list = new HashSet<string>(); is declared in the Start function which makes it a local variable so you won't be able to access it outside that function. Declare it out the Start function so that you can access it from the CreateUser function:


To send your HashSet, loop over it and call form.AddField to add the current HashSet to the form. Use "list[]" (notice the '[]') as the field name in the AddField function so that you can easily access the HashSet on the server side(with php) as follow:

$_POST['list'][0];
$_POST['list'][1];
$_POST['list'][2];

Something like this:

string CreateUserURL = "localhost:81/ARFUR/InsertUser.php";
HashSet<string> list = new HashSet<string>();

string inputUserName = null;
string inputPassword = null;

// Use this for initialization
void Start()
{

}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space)) CreateUser(inputUserName, inputPassword);
}

public void CreateUser(string username, string password)
{
    WWWForm form = new WWWForm();
    list.Add(username);
    list.Add(password);

    //Loop through each one and send
    foreach (var item in list)
    {
        //Add each one to the Field
        form.AddField("list[]", item);
    }

    WWW www = new WWW(CreateUserURL, form);
}

While this may solve your issue, I suggest you use json to serialize your data then send the data instead of your current method. See the POST request with Json section from this post for how to send data as json to the server from Unity.

Programmer
  • 121,791
  • 22
  • 236
  • 328