Unity Code
Scorestr not passing to php variables only $qfName is being saved in query. I am new to both php and unity. maybe explained or simple answers would be appreciated. :)
public GameObject gamectrl;
public void CallRegister()
{
StartCoroutine(Register());
}
IEnumerator Register()
{
List<IMultipartFormSection> wwwForm = new List<IMultipartFormSection>();
int var = gamectrl.GetComponent<GameController>().Score;
string scorestr = var.ToString();
//UnityEngine.Debug.Log(abc);
wwwForm.Add(new MultipartFormDataSection("score", scorestr));
UnityWebRequest www = UnityWebRequest.Post("http://localhost/testphp/HighScore.php", wwwForm);
yield return www.SendWebRequest();
}
php code
<?php
include 'connectivity.php';
$_POST["score"] = 1;
$unityscore = $_POST["score"] ;
$qfName = 'queryrunning';
$insertscorequery = "INSERT INTO highscore (FirstName, HighScore ) VALUES ('$qfName' , '$unityscore' )";
mysqli
_query($con,$insertscorequery);
?>
Related
for my unity game i am trying to make an end score screen where at the end of a level the players imputed name and score are put into a database. i have linked all the game objects correctly but the script doesn't even give an error code and i cant see what i have missed. i have now tried without the adding the score (only adding a imputed name) but i still get the same issue
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class AddScore : MonoBehaviour
{
public InputField nameField;
public GameObject Time;
public GameObject ScoreText;
public Button submitScore;
public void InputScore()
{
StartCoroutine(Register());
}
IEnumerator Register()
{
WWWForm form = new WWWForm();
form.AddField("name", nameField.text);
UnityWebRequest www = UnityWebRequest.Get("https://localhost/sqlconnect/addscore.php");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.LogError(www.error);
}
else
{
Debug.Log("Score added");
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
}
}
public void VerifyInputs()
{
submitScore.interactable = (nameField.text.Length <= 8);
}
}
i can't tell if it is an issue with the php or the c# code so i put them both up here
<?php
$con = mysqli_connect('localhost', 'root', 'password', 'Leaderboard');
if (mysqli_connect_error())
(
echo"1; Connection failed";
exit()
)
$username = $_POST["name"];
$insertuserquery = "INSERT INTO addscore(username) VALUES ('" . $username . "');";
mysqli_query($con, $insertuserquery) or die("4: Insert addscore query failed");
echo("0")
?>
You are doing a GET request without any body:
UnityWebRequest www = UnityWebRequest.Get("https://localhost/sqlconnect/addscore.php");
You should be doing a POST request with the username parameter in the body
Unity POST data
Example Code:
WWWForm form = new WWWForm();
form.AddField("name", "myUserName");
using (UnityWebRequest www = UnityWebRequest.Post("https://localhost/sqlconnect/addscore.php", form))
{
yield return www.SendWebRequest();
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!");
}
}
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
Item.cs
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.
I'm really new into PHP and SQL and I'm trying to learn how to use them with Unity.
First I created a new table in my database with Unity which worked OK. Now I want to update this table with some info, this info should come from Unity.
But it's not working; I'm not sure if it's my C# script or my PHP script.
First, here's a snippet from my C# script:
IEnumerator InsertMemberData(string username,string day,int sale)
{
//insert data to table
WWWForm form = new WWWForm();
form.AddField("usernamePost", username);
form.AddField("currentDayPost", day);
form.AddField("daySalePost", sale);
UnityWebRequest www = UnityWebRequest.Post(updateDataTable, form);
yield return www.Send();
if (www.isError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!");
}
}
and now my PHP script
<?php
$servername = **********
$server_username = ***************
$server_password = ****************
$dbName = *****************
$username = $_POST["usernamePost"];
$currentDay = $_POST["currentDayPost"];
$daySale = $_Post["daySalePost"];
//Make Connection
$conn = new mysqli($servername, $server_username, $server_password, $dbName);
//Check Connection
if(!$conn)
{
die("Connection Failed". mysqli_connect_error());
}
$sql = "Update tbl_{$username} SET ".$currentDay." = ".$daySale." WHERE id=1";
$result = mysqli_query($conn, $sql);
if(!$result){
mysqli_error($conn);
echo "there was an Error!";
}
else echo "Evereything ok.";
?>
I just want to send in a specific table at a specific day a number.
I re-thought my work. So no table for every user, only on Table with all user/userinfos and thinks a want to save/load.
C# script is more or less the same:
IEnumerator InsertMemberData(string username,string day,int sale)
to
IEnumerator InsertMemberData(string username,string day,**string** sale)
and my PHP script :
if($conn)
{
$sqlCheck = "SELECT ID FROM userinfo WHERE username = '".$username."' ";
$resultCheck = mysqli_query($conn,$sqlCheck);
if($resultCheck){
if(mysqli_num_rows($resultCheck)>0)
{
$sqlUpdate = "UPDATE userinfo SET {$day} = '".$value."' WHERE username = '".$username."' ";
$resultUpdate = mysqli_query($conn,$sqlUpdate);
if($resultUpdate)
{
echo("Update success");
}else
{
echo("Update Failed");
}
}
}else{
echo("There was an Error.");
}
}
I'm not really sure why, but this worked perfect for me.
I want to update my score using php with unity
I have session_score.php
<?php
//session_score.php
session_start();
$score = $_REQUEST['score'];
$userid = $_SESSION['userid'];
if (!isset($_SESSION['userid'])) return;
$mysqli = new mysqli("127.0.0.1", "graduate", "bitnami", "my_game");
$sql = "update UserAccount set score=$score where userid='$userid';";
$result = $mysqli->query($sql) or die("first query error");
$sql = "select userid, score from UserAccount;";
$result = $mysqli->query($sql) or die("second query error");
while ($row = $result->fetch_object())
{
echo"{$row->userid} : {$row->score}\n";
}
?>
and this is unity C# code that is attached to the UI button
int score;
public void Score()
{
WWWForm form = new WWWForm();
form.AddField("score", score);
WWW w = new WWW("http://localhost/session_score.php", form);
}
when I click button,the score does not update..
I don't know the reason
please help..
Okay I am using Unity To create my application and MSSQL for the database in between them both i have a PHP Exchange server.
So basically I am having a problem with this piece of code
using UnityEngine;
using System.Collections;
public class NewSession : MonoBehaviour {
string userLoginFile = "http://"ServerIP"/UnitySQL/NewSession.php?";
public UnityEngine.UI.Text NewSess;
string userid = "";
string session = "";
void OnGUI()
{
session = NewSess.text;
userid = PlayerPrefs.GetString ("UserId");
}
public void Insert()
{
if (session == "") {
StartCoroutine (LoginUser (userid));
} else {
print("DAMNSON");
}
}
IEnumerator LoginUser(string user)
{
WWW login = new WWW (userLoginFile + "UserId=" + user);
print (userLoginFile + "UserId=" + user);
yield return login;
if (login.error == null)
{
string[] credentials = login.text.Split('/');
foreach(string str in credentials)
{
string[] creds = str.Split ('=');
for(int i=0; i < creds.Length; i++)
{
print ("winner");
}
}
}
}
}
Now I don't know why its having this problem because it works fine when i use localhost and have the php exchange on my server i can clearly see the scripts print is correct because if i copy and paste that into the address header it does what its supposed to no problem.
Here is the PHP Script
<?php
$userid = $_REQUEST['UserId'];
$user = 'user';
$pass = 'Pass';
$server = 'IP';
$database = 'MyTable';
// No changes needed from now on
$connection_string = "DRIVER={SQL Server};SERVER=$server;DATABASE=$database";
$conn = odbc_connect($connection_string,$user,$pass);
/*$q = "DECLARE #return_value int
EXEC #return_value = [dbo].[InsertAnswersCheck]
#varQuestionOptionId = '$QOI',
#varUser = '$userid'
SELECT 'Return Value' = #return_value";*/
$q = "INSERT INTO usersession (UserId) VALUES ($userid)";
$result = odbc_exec($conn,$q);
$num_rows = odbc_num_rows($result);
if($num_rows > 0)
{
} else {
}
?>
It's been a problem for sometime but i cant figure out what is wrong. If anyone can help that would be fantastic.
Please Note It works with the same script on my localhost if set it will require the user to login twice. But when i do it on the server script it will just stick you in a loop until you copy and paste the print code.
I don't know, but you could try:
Open in browser whatever your print (userLoginFile + "UserId=" + user); prints out.
Put print(login.text); after yield return login; (inside the next if).
Put else you your if (login.error == null) with print("Err: " + "login.error.ToString());
I don't see any echo in your PHP script.
Output form 1 and 2 should be identical.