i have set up my DB and my application in Unity 5. How i need to be able to change the data in the database from Unity. How can i do that? I am using c# in Unity and php for DB (phpMyAdmin). I'll post my php and c# code with a picture of the DB (early stages).
Data/information i want to be able to change (Excuse me that it stands on Norwegian)
php code:
<?php
header("Content-type: text/html; charset=UTF-8");
$servername = "localhost";
$username = "root";
$password = "";
$dbName = "bh";
$CheckForBaasnr = "ChkForBaasnr";
//Make Connection
$conn = new mysqli ($servername, $username, $password, $dbName);
$conn->set_charset('utf8');
//Check Connection
if(!$conn)
{
die("Connection Failed.". mysqli_connect_error());
}
if($_REQUEST['sql'] = "Baasnr")
{
$NoeAnnet = $_GET['sql'];
$_REQUEST['sql']= "SELECT ID, Medlemsnr, EierFNavn, EierENavn, EierAdresse, EierPnr, EierPSted, EierTLF, EierRolle, Pirnr, Baasnr, Naustnr, Opplaggsplassnr, Baattype, Baatmerke, Baatmodell, BaatAarsmodell, BaatStr, Strom, BaasPris, PrisMnd, Vakt, DugnadsTimer, EierEpost FROM medlem WHERE Baasnr = ".$NoeAnnet;
$result = mysqli_query ($conn ,$_REQUEST['sql']);
}
if(mysqli_num_rows($result) > 0){
//show data for each row
while ($row = mysqli_fetch_assoc($result))
{
echo "#".$row['ID']. "#".$row['Medlemsnr']."#".$row['EierFNavn']. "#".$row['EierENavn']. "#".$row['EierAdresse']."#".$row['EierPnr']."#".$row['EierPSted']. "#".$row['EierTLF']."#".$row['EierRolle']."#".$row['Pirnr']."#".$row['Baasnr']."#".$row['Naustnr']."#".$row['Opplaggsplassnr']. "#".$row['Baattype']."#".$row['Baatmerke']."#".$row['Baatmodell']."#".$row['BaatAarsmodell']."#".$row['BaatStr']."#".$row['Strom']."#".$row['BaasPris']."#".$row['PrisMnd']."#".$row['Vakt']."#".$row['DugnadsTimer']. "#".$row['EierEpost']."#";
}
}
?>
C# code:
Well here is a problem. I can't figure out how to do this part!
Hope this explanation was clear enough!
Related
I want to send a converter request via ethernet.
I write a small piece of php.
code:
public function actionModbus()
{
$errors = array();
$warnings = array();
$connection = BinaryStreamConnection::getBuilder()
->setPort(80)
->setHost('192.168.56.205')
->setReadTimeoutSec(3) // increase read timeout to 3 seconds
->build();
$startAddress = 2165;
$quantity = 1;
$slaveId = 1; // RTU packet slave id equivalent is Modbus TCP unitId
$tcpPacket = new ReadHoldingRegistersRequest($startAddress, $quantity, $slaveId);
$rtuPacket = RtuConverter::toRtu($tcpPacket);
try {
$binaryData = $connection->connect()->sendAndReceive($rtuPacket);
$warnings[] = 'RTU Binary received (in hex): ' . unpack('H*', $binaryData)[1] . PHP_EOL;
$response = RtuConverter::fromRtu($binaryData);
$warnings[] = 'Parsed packet (in hex): ' . $response->toHex() . PHP_EOL;
$warnings[] ='Data parsed from packet (bytes):' . PHP_EOL;
print_r($response->getData());
}catch (\Exception $exception)
{
$errors[] = $exception->getMessage();
$errors[] = $exception->getLine();
}finally {
$connection->close();
}
$result = array('errors'=>$errors,'warnings'=>$warnings);
Yii::$app->response->format = Response::FORMAT_JSON;
Yii::$app->response->data = $result;
}
But I want to write one in C#.
Please tell me a library or an example in C#
There are quite a few libraries available including EasyModbus and NModbus4 both of which have good documentation and samples (and are mentioned in recent stackoverflow questions).
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.
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!
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
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.