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.
Related
Im doing a project where you can create an accoun, log in an save user data in unity using php and a mysql server. I did all the registering process and it worked but I cant get the login working. Im doing this following the boardtobits tutorial.
Doing some research I have read that the hash generated when created the account and the loginhash are not the same, but why?
PHP CODE - (for login)
<?php
$user = 'root';
$password = 'root';
$db = 'hostalvillegadata';
$host = 'localhost';
$port = 8889;
$link = mysqli_init();
$success = mysqli_real_connect(
$link,
$host,
$user,
$password,
$db,
$port);
//check that connection happened
if (mysqli_connect_errno())
{
echo "1: Connection failed"; //error code #1 = connection failed
exit();
}
$username = $_POST["name"];
$password = $_POST["password"];
//check if name exists
$namecheckquery = "SELECT username, salt, hash, habitacionesreservadas
FROM hostalvillegatable WHERE username='" .$username. "';";
$namecheck = mysqli_query($link, $namecheckquery) or die("2: Name check
query failed"); // error code #2 - name check query failed
if (mysqli_num_rows($namecheck) != 1 )
{
echo "5: No user with name, or more than one"; //error code #5 - number
of names matching != 1
exit();
}
//get login info from query
$existinginfo = mysqli_fetch_assoc($namecheck);
$salt = $existinginfo["salt"];
$hash = $existinginfo["hash"];
$loginhash = crypt($password, $salt);
if ($hash != $loginhash)
{
echo "6: Incorrect password"; //error code #6 - password does not
hash to match table
exit();
}
echo "0\t" . $existinginfo["habitacionesreservadas"];
?>
C# CODE-(Login)
public class LogIn : MonoBehaviour
{
public InputField nameField;
public InputField passwordField;
public Button submitButton;
public void CallLogin()
{
StartCoroutine(Login());
}
IEnumerator Login()
{
WWWForm form = new WWWForm();
form.AddField("name", nameField.text);
form.AddField("password", nameField.text);
UnityWebRequest www = UnityWebRequest.Post("http://localhost:8080/sqlconnect/login.php", form);
yield return www.SendWebRequest();
if (www.downloadHandler.text[0] == '0')
{
DataBaseManager.username = nameField.text;
DataBaseManager.habitacionesreservadas = int.Parse(www.downloadHandler.text.Split('\t')[1]);
}
else
{
Debug.Log("User login failed. Error #" + www.downloadHandler.text);
}
}
public void VerifyInputs()
{
submitButton.interactable = (nameField.text.Length >= 5 && passwordField.text.Length >= 5);
}
}
C# CODE (DataBaseManager)
public static class DataBaseManager
{
public static string username;
public static int habitacionesreservadas;
public static bool LoggedIn {get { return username != null; } }
public static void LogOut()
{
username = null;
}
It should work and login the user but instead it tells me the password is incorrect, I have created several account with same password an no changes.
Any idea how to solve this?
this line
$existinginfo = msqli_fetch_assoc($namecheck);
must be
$existinginfo = mysqli_fetch_assoc($namecheck);
i'm new to MySQL system. I have to store in a database:
Username;
Score;
Resources.
For send username, score and resources i don't have any problems but whene i try to get resources from database i have this error:
</style>
</head>
<body>
<h1>Bad request!</h1>
<p>
Your browser (or proxy) sent a request that
this server could not understand.
</p>
<p>
If you think this is a server error, please contact
the webmaster.
</p>
<h2>Error 400</h2>
<address>
localhost<br />
<span>Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/7.1.1</span>
</address>
</body>
</html>
UnityEngine.Debug:Log(Object)
<SetPlayerName>c__Iterator1:MoveNext() (at Assets/Scripts/DataBase/MySQL/DBLoader.cs:67)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)
This is my php file:
<?php
$servername = "host";
$username = "name";
$password = "";
$dbname = "game_name";
$coinsname = (isset($_REQUEST['coinsnameGet']) ? $_REQUEST['coinsnameGet'] : null);
//Create Connection
$connection = new mysqli($servername, $username, $password, $dbname);
//Check Connection
if(!$connection) {
die("Connection Failed. " . mysqli_connect_error());
}
$sql = "SELECT Coins FROM score WHERE Name = '" . $coinsname . "'";
$result = mysqli_query($connection, $sql);
while($row = mysqli_fetch_array($result, MYSQLI_BOTH) {
echo $row['Coins'];
}
?>
I have to check if name is == to local database name then get resources.
The local db is made with sqlite.
And this is my connected class:
private DataBase dbLocal;
WWW userData;
WWW scoreData;
WWW coinsData;
public Text Coins;
private string[] dbUsers;
private string[] dbScores;
private string dbCoins;
private string postCoinsData = "http://host/game_name/UsercoinsData.php";
public GameObject scorePrefab;
public Transform scoreParent;
public GameObject rankValue;
public GameObject nameValue;
public GameObject scoreValue;
// Use this for initialization
IEnumerator Start () {
dbLocal = (DataBase)FindObjectOfType(typeof(DataBase));
userData = new WWW("http://host/game_name/UsernameData.php");
scoreData = new WWW("http://host/game_name/UserscoreData.php");
yield return userData;
yield return scoreData;
string textUserData = userData.text;
dbUsers = textUserData.Split(';');
string textScoreData = scoreData.text;
dbScores = textScoreData.Split(';');
scoreParent.transform.localPosition = new Vector3(0, 0, 0);
dbLocal.Connection();
StartCoroutine(SetPlayerName());
GenerateScore();
}
IEnumerator SetPlayerName()
{
string setName = postCoinsData + "coinsnameGet = " + WWW.EscapeURL(dbLocal.GetName());
WWW dataCoins = new WWW(setName);
Debug.Log(dbLocal.GetName());
yield return dataCoins;
string textDataCoins = dataCoins.text;
Coins.text = textDataCoins;
Debug.Log(Coins.text); //This log the error
}
If i change this:
$sql = "SELECT Coins FROM score WHERE Name = '" . $coinsname . "'";
with this:
$sql = "SELECT Coins FROM score WHERE Name = 'PlayerName'";
In brower i see the score.
Thx in advance!
Your php will never find the $_REQUEST['coinsnameGet'] because you're creating the URL like this:
string setName = postCoinsData + "coinsnameGet = " + WWW.EscapeURL(dbLocal.GetName());
which will look something like:
http://host/game_name/UsercoinsData.phpcoinsnameGet = PlayerName
but should look like
http://host/game_name/UsercoinsData.php?coinsnameGet=PlayerName
Not entirely sure if this is what's causing your issues or if it's a copy-paste error, but if it is, your code should be changed to:
string setName = postCoinsData + "?coinsnameGet=" + WWW.EscapeURL(dbLocal.GetName());
I have here a Login I am currently working on, just having a small issue with my PHP I think.
My php for the connection to DB:
<?php
$db_name = "mydata";
$mysql_username = "root";
$mysql_password = "";
$server_name = "localhost";
$conn = mysqli_connect($server_name, $mysql_username, $mysql_password, $db_name);
if($conn){
echo
"Connection Succesful";
}
else{
echo "Connection Not Succesful";
}
?>
My php for the actual login:
<?php
require "conn.php";
$Email = $_POST["emailPost"];
$Password = $_POST["passwordPost"];
$sql = "SELECT Password FROM users WHERE Email = '".$Email."' ";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
if($row == $Password){
echo "login success";
}
else{
echo "Password incorrect";
}
}
}else{
echo "user not found";
}
?>
and finally the Coroutine I am using in my C#
IEnumerator LoginAccount()
{
WWWForm Form = new WWWForm();
Form.AddField("emailPost", Email);
Form.AddField("passwordPost", Password);
WWW www = new WWW(LoginUrl, Form);
yield return www;
Debug.Log(www.text);
}
I get Password incorrect every single time. What am I missing ?
found it!
if($row[Password] == $Password)
Use this code (make sure to update this $row[Password] same as the password field name)
<?php
require "conn.php";
$Email = $_POST["emailPost"];
$Password = $_POST["passwordPost"];
$sql = "SELECT Password FROM users WHERE Email = '".$Email."' ";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
if($row['Password'] == $Password)
{
echo "login success";
}
else
{
echo "Password incorrect";
}}}
else
{
echo "user not found";
}
?>
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.