Unity is not changing SQL database value - c#

I got this php on my server, that is called to run when I click on a button to add currency:
// Select player_name
$check = mysqli_query($conn,"select Currency from player where Name='$player_name'");
$checkrows=mysqli_num_rows($check);
if($checkrows==1) {
$sql = "INSERT INTO player (Currency) VALUES ('post_player_currency')";
$result = mysqli_query($conn, $sql) or die('Error querying database.');
echo ("DATABASE: Currency added ");
} else {
// Insert player into database
echo "DATABASE: Currency NOT added ";
}
?>
And on my Unity C# script, I have this:
public IEnumerator AddCurrency(Text playername, Text playercurrency) {
_tempCoins = int.Parse(coins.text);
_tempCoins += 10;
coins.text = _tempCoins.ToString();
WWWForm form = new WWWForm ();
form.AddField ("post_player_name", playername.text);
form.AddField ("post_player_currency", playercurrency.text);
WWW www = new WWW (RegisterPlayerURL, form);
yield return www;
print (www.text);
if (www.text == "DATABASE: Currency added ") {
print ("TRANSACTION: Current Coins: " + _tempCoins);
}
}
The scripts themselves are working, but what I don't understand is why I get Error querying database. everytime as result, instead of it actually adding the value to the database.
A very similar script to register a player to the database that I made, is working just fine. I've spent a lot of time and I cannot figure out why this one doesn't work.
Help is appreciated! Thanks!

Related

c# Wait until co routine is finished before executing code [duplicate]

This question already has answers here:
Unity - need to return value only after coroutine finishes
(3 answers)
Closed 5 years ago.
Hi im trying to implement saving/loading from sql database into my game.
i have it all working apart from the fact that i need to hit load twice for it to load the data.
the code to set the data finishes before i have a chance to set it.
public void loadData()
{
GetComponent<SavingLoading>().Load(GameObject.Find("LoginSystem").GetComponent<LoginSystem>().Username);
if (GetComponent<SavingLoading>().LoadedData != "")
{
string[] Data = GetComponent<SavingLoading>().LoadedData.Split(',');
Level = Convert.ToInt32(Data[0]);
CurrentXp = Convert.ToInt32(Data[1]);
currentHealth = Convert.ToInt32(Data[2]);
maxHealth = Convert.ToInt32(Data[3]);
Vector3 LoadedPos = new Vector3(Convert.ToSingle(Data[4]), Convert.ToSingle(Data[5]), Convert.ToSingle(Data[6]));
transform.position = LoadedPos;
}
}
Theese functions are in another script.
public void Load(string name)
{
StartCoroutine(LoadCall(name));
}
IEnumerator LoadCall(string name)
{
WWWForm form = new WWWForm();
form.AddField("name", name);
WWW www = new WWW(LoadPhP, form);
yield return www;
string _return = www.text;
LoadedData = _return;
}
how can i go about only updating the data if there is data present? without having to press the load button twice.
According to the docs, you should wrap the www variable in a using statement in order to properly disposeit. Then yield return on it, like so:
using (WWW www = new WWW(url))
{
yield return www;
string _return = www.text;
LoadedData = _return;
}
I am not sure what you mean by 'only updating the data if there is data present'. Do you have more code to show that might help to clarify your intent?

Connect Unity App to mySQL database

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();
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.

Not posting to database

I'm pretty new with this Database / server stuff, so please bear with me. I'm having trouble figuring out why these variables aren't posting to my DB from Unity.
My DB connection information is correct, as other posts are working.
here's my php:
- I've replaced the $_POST variables below with non-post variables and they work just fine! So I'm relatively happy with my php code.
<?php
$servername = "localhost";
$DBusername = "id*****_zingzingzingbah";
$DBpassword = "*******";
$DBName = "id430563_fitness2017";
$firstname = $_POST["firstnamePOST"];
$lastname = $_POST["lastnamePOST"];
$username = $_POST["usernamePOST"];
$email = $_POST["emailPOST"];
$password = $_POST["passwordPOST"];
//$firstname = "aaaa";
//$lastname = "aaaa";
//$username = "aaaa";
//$email = "aaaa";
//$password = "aaaa";
// Make Connection
$conn = new mysqli($servername,$DBusername, $DBpassword, $DBName);
// Check Connection
if (!$conn) {
die ("Connection Failed. ". mysqli_connect_error());
} else { echo "Connection Success" ; // display some text or info on the screen }
$sql = "INSERT INTO user_info (firstname, lastname, username, email, password) VALUES('".$firstname."','".$lastname."','".$username."','".$email."','".$password."')";
$result = mysqli_query($conn, $sql);
if(!$result) {
echo "there was an error creating user specific table";
} else {
echo "Everything OK2";
}
?>
See Unity C# code below...
- I have two CreateUser functions below so that the void one, can be accessed from Unity... I had trouble accessing IEnumerator functions otherwise.
- the code gets stuck after insertUserInfo = new WWW (InsertUserInfoURL,form);
- the yield return isn't returning.
public void CreateUser(string inputFirstname, string inputLastname, string inputUsername,string inputEmail,string inputPassword ){
StartCoroutine (CreateUser2 (inputFirstname,inputLastname,inputUsername,inputEmail,inputPassword));
}
private IEnumerator CreateUser2(string inputFirstname, string inputLastname, string inputUsername,string inputEmail,string inputPassword ){
WWWForm form = new WWWForm ();
inputFirstname = "bbb";
inputLastname = "bbb";
inputUsername = "bbb";
inputEmail = "bbb";
inputPassword = "bbb";
form.AddField ("firstnamePOST", inputFirstname);
form.AddField ("lastnamePOST", inputLastname);
form.AddField ("usernamePOST", inputUsername);
form.AddField ("emailPOST", inputEmail);
form.AddField ("passwordPOST", inputPassword);
print("getting here ok");
insertUserInfo = new WWW (InsertUserInfoURL,form);
yield return insertUserInfo;
print("why aren't you getting here");
I'm sure the URL is correct (base on test without POST variables)
I'm sure the DB info is correct (base on test without POST variables)
I'm sure the SQL code is correct (base on test without POST variables)
I'm definitely calling the CreateUser functions (both of them)
would appreciate any tips on troubleshooting this stuff, because I feel like I'm fumbling in the dark
thanks guys!
Ok, so I finally figured it out...
I was changing my scene in Unity before the WWW request had time to resolve..
probably down to horrible coding on my behalf!
thanks everyone for your comments

How to send data form to server using json in unity

I want to using json to send the form to my server
here is my C# code
public string db_url="http://localhost/";
IEnumerator SaveAllPlayerPrefs(object[] parms)
{
string ourPostData = "{\"bone\":\"42\"}";
Hashtable headers = new Hashtable();
headers.Add("Content-Type", "application/json");
headers.Add("Cookie", "Our session cookie");
byte[] pData = System.Text.Encoding.UTF8.GetBytes(ourPostData);
WWW webRequest = new WWW(db_url + "SaveAllPlayerPref.php", pData, headers);
yield return webRequest;
}
and here is my php code:
<?php
$sql_connect = mysql_connect("localhost", "root", "") or die ("no DB Connection");
mysql_select_db("example") or die ("DB not found");
$bone = $_POST['bone'];
mysql_query("INSERT INTO save_game (bone) VALUES ('$bone');");
mysql_close($sql_connect);
?>
When i run it this code its running, but when i check the database, its not save the value of bone. It's save the empty string to bone, i want it to save 42..
it insert new row in my database, but with empty value of "bone"
in my database bone is varchar(100) and utf8_general_ci.
Can someone explain to me?
thx before:)
Try var_dump($_POST) to see what you receive.

Calling Json script and displaying the Images within the script

I'm trying to access a Json script, it is in a domain. The script holds a couple of images, which are hyperlinked. I've tried using WWW to access the script, but the image i received was a picture of a huge red question mark. Clearly I'm going about the wrong way with this. So i'm assuming I'm supposed to decode the json script through unity and then display the image with the ability to see next/previous image by clicking? I'm unfamiliar with Json so how about would i call the script and read the the images it's calling?
This is what my code looks like, the code works since I've tried another non Json domain with just an image- and it works perfectly fine.
void Start ()
{
renderer.material.mainTexture = new Texture2D(4,4, TextureFormat.DXT1, false);
url = "http://hosting.xivmedia.com/JsonHome/JSON/more_games.json";
www = new WWW(url);
StartCoroutine(WaitForSeconds(www));
}
IEnumerator WaitForSeconds(WWW www)
{
yield return www;
www.LoadImageIntoTexture(renderer.material.mainTexture as Texture2D);
if (www.error == null)
{
Debug.Log("WWW Ok!: " + www.data);
imageLoaded = true;
}
else
{
Debug.Log("WWW Error: " + www.error);
}
}
void OnGUI()
{
GUI.DrawTexture(new Rect(20, 80, 100, 100), renderer.material.mainTexture as Texture2D, ScaleMode.StretchToFill);
}
Yes, as you said correctly, you'll need to decode the JSON script first. You'll need a JSON parser to do that. The one I highly recommend is JSON .NET For Unity, but MiniJSON should do just fine.
So, assuming your json is just a list of URLs as so:
[
"http://.....",
"http://....."
]
With JSON.NET you would modify your code as follows:
IEnumerator WaitForSeconds(WWW www)
{
yield return www;
string json = www.text;
List<string> imageUrls = JsonConvert.Deserialize<List<string>>(json);
foreach (string imageUrl in imageUrls)
{
WWW imageWWW = new WWW(imageUrl);
imageWWW.LoadImageIntoTexture(renderer.material.mainTexture as Texture2D);
if (imageWWW .error == null)
{
Debug.Log("WWW Ok!: " + imageWWW.data);
imageLoaded = true;
}
else
{
Debug.Log("WWW Error: " + imageWWW.error);
}
}
}
If the JSON is more complicated, you can create a class that the JSON can deserialize to. I.e., if the JSON is a list of objects as so:
[
{
"name": "test",
"url" : "http://...."
},
{
"name": "something",
"url" : "http://..."
}
]
Then you would have a simple class
public class ImageData
{
public string name;
public string url;
}
And deserialize the JSON as so
List<ImageData> imageUrls = JsonConvert.Deserialize<List<ImageData>>(json);
foreach (ImageData data in imageUrls)
{
WWW imageWWW = new WWW(data.url);
imageWWW.LoadImageIntoTexture(renderer.material.mainTexture as Texture2D);

Categories