I'm trying to set up my Account registration system to input data from unity to my database, and so far i have been able to do so through the Inspector, now I want to be able to do this with my UI that i made in Unity, what do I need to do? (P.S. this is my first time posting and i am also a beginner so excuse me if i may not follow some rules and what not)
here is the code i used to input data to my PhpMyAdmin database through the inspector in Unity:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DataInserter : MonoBehaviour
{
public GameObject inputUserName;
public GameObject inputEmail;
string CreateUserURL = "http://localhost/balikaral/insertAccount.php";
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space)) CreateUser(inputUserName, inputEmail);
}
public void CreateUser(string username, string email)
{
WWWForm form = new WWWForm();
form.AddField("usernamePost", username);
form.AddField("emailPost", email);
WWW www = new WWW(CreateUserURL, form);
}
}
You simply have to get the input from your input fields InputField.text
I recommend to directly use InputField
fields so you don't need the GetComponent
calls.
public class DataInserter : MonoBehaviour
{
public InputField inputUserName;
public InputField inputEmail;
string CreateUserURL = "http://localhost/balikaral/insertAccount.php";
public void CreateUser()
{
var userName = inputUserName.text;
var email = inputEmail.text;
WWWForm form = new WWWForm();
form.AddField("usernamePost", username);
form.AddField("emailPost", email);
WWW www = new WWW(CreateUserURL, form);
}
}
And reference the CreateUser
method in the Button's onClick
event.
Note however that WWW
is obsolete and you should rather use UnityWebRequest.Post
public void CreateUser()
{
var userName = inputUserName.text;
var email = inputEmail.text;
StartCoroutine(CreateUserRequest(userName, email));
}
private IEnumerator CreateUserRequest(string userName, string email)
{
WWWForm form = new WWWForm();
form.AddField("usernamePost", username);
form.AddField("emailPost", email);
using (UnityWebRequest www = UnityWebRequest.Post(CreateUserURL, form))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!");
}
}
}