MySQL is adding space in front of string - c#

So i'm using MySQL and C# in order to grab info from a database, but when i try to use that database info again in MySQL doesn't work because it seems to be adding a small space in front of the data. Let me show you what i mean.
php code that displays info on webpage
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$nick = $_POST["myform_nick"];
$sql = "SELECT Lin FROM scores WHERE name='$nick'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["Lin"];
}
}
Then in C# it is like this...
IEnumerator LeagueCheck(){
var form = new WWWForm ();
form.AddField( "myform_nick", formNick );
WWW w = new WWW (URL, form);
yield return w;
if (w.error != null) {
print(w.error); //if there is an error, tell us
}
else {
print("League Check 1");
LinII = w.text; //here we return the data our PHP told us
print (w.text);
Lin = LinI + LinII;
w.Dispose(); //clear our form in game
StartCoroutine (LeagueCheck2 ());
}
}
Inside LeagueCheck2 it uses LinII to grab another thing from the database but it can't find it because it comes back like this
" Dominators"
instead of like this
"Dominators"
So my question is how can i get it to remove that little space in front of Dominators.
What i've tried to fix this
using System;
LinII = String.Trim(w.text);
LinII = w.text;
LinII.Trim();
LinII.Replace(" ","");
void Timer(){
LinII.Trim();
}
//In the IEnumator LeagueCheck();
Lin = LinI + LinII;
w.Dispose(); //clear our form in game
Trimer();
StartCoroutine (LeagueCheck2 ());

This should work if w.text and LinII are a string
if (w.error != null) {
print(w.error); //if there is an error, tell us
}
else {
print("League Check 1");
LinII = w.text.Trim(); //here we return the data our PHP told us
print (LinII );
Lin = LinI + LinII;
w.Dispose(); //clear our form in game
StartCoroutine (LeagueCheck2 ());
}

Related

WWW.bytesDownloaded doesnt update while loading

In my script im expecting the text bytesDownloadedText to be updated with how many bytes have been downloaded so far but it only runs once and stays on 0. How do I fix this
private IEnumerator DownloadFile(){
WWW w = new WWW (PATH_TO_DOWNLOAD);
bytesDownloadedText.text = w.bytesDownloaded.ToString();
yield return w;
if (w.error != null) {
Debug.LogError ("Error: " + w.error);
} else {
scriptText = w.text;
filesDownloaded = true;
Debug.Log (scriptText);
}
}
Edit: New code + Additional debugging information
private IEnumerator DownloadFile(){
WWW w = new WWW (PATH_TO_DOWNLOAD);
while(!w.isDone){
bytesDownloadedText.text = w.bytesDownloaded.ToString ();
Debug.Log ("Bytes Downloaded: " + w.bytesDownloaded);
yield return null;
}
Debug.Log ("Exiting while loop");
if (w.error != null) {
Debug.LogError ("Error: " + w.error);
} else {
//bytesDownloadedText.text = w.bytesDownloaded.ToString ();
scriptText = w.text;
filesDownloaded = true;
Debug.Log (scriptText);
}
}
Filesize: 337 bytes
Download Path: https://deathcrow.altervista.org/websharp/files.php
3.Code where DownloadFile is called
private void Start(){
StartCoroutine (DownloadFile ());
}
The while loop is exiting
w.text returns the test script from the server(which is code)
using UnityEngine;
public class TestScript: MonoBehaviour{
public void Update(){
if (Input.GetMouseButtonDown (0)) {
RaycastHit hit;
if (Physics.Raycast (Camera.main.ScreenPointToRay(Input.mousePosition),out hit)){
if (hit.transform.tag == "Destroy") {
Destroy (hit.transform.root.gameObject);
}
}
}
}
}
Edit: Online code
<?
$scriptText = "";
$file_handle = fopen("TestScript.cs","r");
while(!feof($file_handle)){
$line = fgets($file_handle);
$scriptText = $scriptText . $line;
}
fclose($file_handle);
$size = strlen($scriptText);
header("Content-length: ".$size);
echo $scriptText;
?>
Do not yield WWW if you want to use the bytesDownloaded property as that will pause your code until WWW returns which makes it impossible to read how much data has been downloaded.
You have to put WWW.bytesDownloaded in a loop then use WWW.isDone to detect when WWW is done and then exit the loop. Inside that loop, you can use WWW.bytesDownloaded to display the downloaded data. Finally, you must wait for a frame after each loop so that other scripts can execute or Unity will freeze until the download is done.
This is what that code should look like:
private IEnumerator DownloadFile()
{
WWW w = new WWW(PATH_TO_DOWNLOAD);
while (!w.isDone)
{
yield return null;
bytesDownloadedText.text = w.bytesDownloaded.ToString();
Debug.Log("Bytes Downloaded: " + w.bytesDownloaded);
}
if (w.error != null)
{
Debug.LogError("Error: " + w.error);
}
else
{
scriptText = w.text;
filesDownloaded = true;
Debug.Log(scriptText);
}
}
Note: There are some instances where the bytesDownloaded property returns 0. This has nothing to do with Unity. This happens mostly when your server is not sending the Content-Length header.
Example of sending the Content-Length header from the server(php):
<?php
//String to send
$data = "Test message to send";
//Get size
$size= strlen($data);
//Set Content-length header
header("Content-length: ".$size);
//Finally, you can send the data
echo $data;
?>

How to send a PUT request using UnityWebRequest?

How do I send a PUT request using UnityWebRequest?
The PUT is being sent; Uploaded!! is being printed to the console. However, nothing is being updated. I think I'm formatting myData incorrectly.
The actual URL I'm trying to send the PUT to is formatted like... http://servername.com/api/dogs/1/token=fndskajfdafdsf&cleanliness_level=20
Sorry, I can't remember what that format is called.
This is the code that I have:
public string url = "http://servername.com/api/dogs/1";
.
.
.
void Start() {
StartCoroutine (UpdateDogs ("clean"));
}
IEnumerator UpdateDogs (string button)
{
byte[] myData;
if (button == "feed") {
myData = System.Text.Encoding.UTF8.GetBytes ("?token=" + token + "&health_level=" + healthLevel);
} else {
myData = System.Text.Encoding.UTF8.GetBytes ("?token=" + token + "&cleanliness_level=" + cleanlinessLevel);
}
using (UnityWebRequest www = UnityWebRequest.Put (url, myData)) {
yield return www.Send ();
if (www.isError) {
Debug.Log ("PUT ERROR: " + www.error);
} else {
Debug.Log ("Uploaded!!");
}
}
It looks like you're missing an & in the parameter string after the token.
token + "cleanliness_level=
Should be
token + "&cleanliness_level=
Similarly for the other possible parameters.
myData in UnityWebRequest.Put is only for http body data. It doesn't seem like you need that. Instead you should add your query parameters to the URL, like such:
public string url = "http://servername.com/api/dogs/1";
if (button == "feed") {
url += "?token=" + token + "&health_level=" + healthLevel;
} else {
url += "?token=" + token + "&cleanliness_level=" + cleanlinessLevel;
}
using (UnityWebRequest www = UnityWebRequest.Put (url, "dummy")) { // UnityWebRequest.Put requires a body, see comments below
yield return www.Send ();
if (www.isError) {
Debug.Log ("PUT ERROR: " + www.error);
} else {
Debug.Log ("Uploaded!!");
}
}
I think you are missing a forward slash before token when you send it.
Try debugging what you actually send with
Debug.Log (www.text);
Next advice is that maybe the error is with what code you use on the back end receiving the data.

Extra character from WWW text (Compare with www.text not working)

I am programming a login system now on Unity, but I have this weird bug. For some reason when I get the output of the php file, the if statement in the C# file can't see that 'loginreturn' (= AccountDoesntExist) and the string "AccountDoesntExist" are the same. I don't know why but maybe you smart people see the bug and can help me out.
C# Code:
IEnumerator TryLogin(string username, string password)
{
WWWForm form = new WWWForm();
form.AddField("username", username);
form.AddField("password", password);
WWW loginWWW = new WWW(LoginURL, form);
yield return loginWWW;
if (!string.IsNullOrEmpty(loginWWW.error))
{
Debug.LogError("Cannot connect to LOGIN servers! Error: " + loginWWW.error);
}else
{
string loginreturn = loginWWW.text;
Debug.Log(loginWWW.text);
Debug.Log(loginreturn);
if (loginreturn == "AccountDoesntExist")
Debug.Log("WORKS!");
}
}
PHP Code (which will always return "AccountDoesntExist" because of the way I log in):
<?php
$inputusername = $_REQUEST["username"];
$password = $_REQUEST["password"];
$servername = "localhost";
$username = "chatsystem_accs";
$password = "CENCORED";
$dbname = "chatsystem_accs";
//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Connected successfully
$sql = "SELECT `username`, `password` FROM `accounts`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($inputusername == $row["username"]) {
if (password_verify($password, $row["password"])) {
echo "Success";
}else {
echo "UsernameOrPasswordIncorrect";
}
}else {
echo "AccountDoesntExist";
}
}
}else {
echo "AccountDoesntExist";
}
//Close connection
$conn->close();
?>
Very likely a UTF-8 problem. There is an extra data in the received bytes. Convert the received data to UTF-8 before comparing it.
Replace
string loginreturn = loginWWW.text;
with
string loginreturn = System.Text.Encoding.UTF8.GetString(loginWWW.bytes, 3, loginWWW.bytes.Length - 3);
EDIT:
Did debugging like this:
Debug.Log("Received Length: "+ loginreturn.Length);
Debug.Log("Compare Length: " + "AccountDoesntExist".Length);
and the results were:
Received Length: 19
Compare Length: 18
This is wrong. There is an extra character somewhere.
Debugged again with the function below then called it with displayAsChar(loginreturn);
void displayAsChar(string badValue)
{
char[] values = badValue.ToCharArray();
for (int i = 0; i < values.Length; i++)
{
string tempResult = "Value at index " + i + " is: " + values[i];
Debug.Log(tempResult);
}
}
It shows there is an empty character at the end of the character. I thought that was just " " but it wasn't.
I made another function to see what this empty character is:
void showStringAsHex(string badValue)
{
foreach (char c in badValue)
Debug.Log("To Unicode: " + ((int)c).ToString("X2"));
}
Bingo. That last character is 0A (Hex) which is also represented as \n. This is used as a line feed.
FIX:
Before doing the compare action, trim the string. This will remove any escape character and empty strings in the beginning and end of the character.
To trim the character, simply add the code below before comparing the string.
loginreturn = loginreturn.Trim();
Why post the debugging process?
The characters might be different for different servers. Posting this will help others troubleshoot and fix this problem for them-selves in the future.

I am getting raw text while reading emails using IMAP

I have taken some code from MSDN to read emails using IMAP Client. I have changed little bit code so i can only read unseen email.
I am writing all response in Richtextbox.
The problems is format of Body text of Email is unreadable while all other text is fine.
void ReadEmail()
{
try
{
// there should be no gap between the imap command and the \r\n
// ssl.read() -- while ssl.readbyte!= eof does not work because there is no eof from server
// cannot check for \r\n because in case of larger response from server ex:read email message
// there are lot of lines so \r \n appears at the end of each line
//ssl.timeout sets the underlying tcp connections timeout if the read or write
//time out exceeds then the undelying connection is closed
tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
ssl = new System.Net.Security.SslStream(tcpc.GetStream());
ssl.AuthenticateAsClient("imap.gmail.com");
receiveResponse("");
username = "charlie#gmail.com";
password = "********";
receiveResponse("$ LOGIN " + username + " " + password + " \r\n");
receiveResponse("$ LIST " + "\"\"" + " \"*\"" + "\r\n");
receiveResponse("$ SELECT INBOX\r\n");
receiveResponse("$ UID SEARCH UNSEEN\r\n");
MatchCollection collection= Regex.Matches(Result,#" (\d{1,4})");
foreach (Match m in collection)
{
UNREAD_UID.Add(int.Parse(m.Groups[1].Value));
}
foreach (int x in UNREAD_UID)
{
receiveResponse("$ FETCH " +x + " body[header]\r\n");
richTextBox1.Text += Environment.NewLine+"-----------------------------------------------------------------------------------------------------------------------"+Environment.NewLine;
receiveResponse("$ FETCH " +x + " body[text]\r\n");
richTextBox1.Text += Environment.NewLine + "###########################################################2" + Environment.NewLine;
richTextBox1.Update();
}
//receiveResponse("$ STATUS INBOX (MESSAGES)\r\n");
// int number = 1;
receiveResponse("$ LOGOUT\r\n");
}
catch (Exception ex)
{
Console.WriteLine("error: " + ex.Message);
}
finally
{
if (sw != null)
{
sw.Close();
sw.Dispose();
}
if (ssl != null)
{
ssl.Close();
ssl.Dispose();
}
if (tcpc != null)
{
tcpc.Close();
}
}
}
void receiveResponse(string command)
{
try
{
if (command != "")
{
if (tcpc.Connected)
{
dummy = Encoding.ASCII.GetBytes(command);
ssl.Write(dummy, 0, dummy.Length);
}
else
{
throw new ApplicationException("TCP CONNECTION DISCONNECTED");
}
}
ssl.Flush();
buffer = new byte[5120];
bytes = ssl.Read(buffer, 0, 5120);
sb.Append(Encoding.ASCII.GetString(buffer));
Result = sb.ToString();
richTextBox1.Text += Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + sb.ToString();
sb = new StringBuilder();
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
}
Here is Sample of what i am getting
108 FETCH (BODY[TEXT] {25656}
DQoNCg0KDQo8IURPQ1RZUEUgaHRtbD4NCjxodG1sPg0KPGhlYWQ+DQo8dGl0bGU+TWlj
cm9zb2Z0IHR1cm5zIChhbG1vc3QpIGFueSBjYW1lcmEgaW50byBhIEtpbmVjdDwvdGl0
bGU+DQo8bWV0YSBodHRwLWVxdWl2PSJDb250ZW50LVR5cGUiIGNvbnRlbnQ9InRleHQv
aHRtbDsgY2hhcnNldD1VVEYtOCI+DQo8bWV0YSBuYW1lPSJ2aWV3cG9ydCIgY29udGVu
dD0id2lkdGg9ZGV2aWNlLXdpZHRoIj4NCjwhLS0gRWZmaW5nIFdpbmRvd3MgOCBNYWls
IGNsaWVudC4gQWRkIC13ZWJraXQtbWluLWRldmljZS1waXhlbC1yYXRpbzogMSB0byBz
Y2FyZSBpdCBhd2F5IGZyb20gdGhpcyBiaXQuIC0tPg0KPHN0eWxlIHR5cGU9InRleHQv
Y3NzIj4NCkBtZWRpYSBzY3JlZW4gYW5kIChtYXgtZGV2aWNlLXdpZHRoOiA1MDBweCkg
YW5kICgtd2Via2l0LW1pbi1kZXZpY2UtcGl4ZWwtcmF0aW86IDEpIHsNCgkuYm9keS1j
b250YWluZXIgeyB3aWR0aDoxMDAlICFpbXBvcnRhbnQ7IH0NCgkuYmFubmVyICAgICAg
ICAgeyBkaXNwbGF5OiBub25lICFpbXBvcnRhbnQ7IH0NCgkubW9iaWxlLWJhbm5lciAg
eyBkaXNwbGF5OiBibG9jayAhaW1wb3J0YW50OyB3aWR0aDozNDBweCAhaW1wb3J0YW50
OyBiYWNrZ3JvdW5kOiB1cmwoaHR0cDovL3d3dy5jb2RlcHJvamVjdC5jb20vc2NyaXB0
L21haWxvdXRzL3RlbXBsYXRlcy9uZXdzbGV0dGVyLWluc2lkZXIucG5nKSBuby1yZXBl
YXQgdG9wIGxlZ
Kindly help me.
You need to examine the Content-Transfer-Encoding header to undo Transfer encoding (in this case, that's Base64. Other alternatives are 7-bit or Quoted Printable). Or, better, download the entire message (Body[]) and apply a MIME parser/decoder to it to get an object representation of the headers, body, and attachments.
Max's answer above is correct, but I'm going to illustrate how to implement his suggestion using my MailKit library:
using (var client = new ImapClient ()) {
client.Connect ("imap.gmail.com", 993, true);
// since we're not using an OAuth2 token, remove it from the set
// of possible authentication mechanisms to try:
client.AuthenticationMechanisms.Remove ("XOAUTH2");
client.Authenticate ("charlie#gmail.com", "*****");
// SELECT the INBOX folder
client.Inbox.Open (FolderAccess.ReadWrite);
foreach (var uid in client.Inbox.Search (SearchQuery.NotSeen)) {
var message = client.Inbox.GetMessage (uid);
// at this point, 'message' is a MIME DOM that you can walk
// over to get the particular MIME-part that you want. For
// example, we could get a body part with a filename of
// "test.txt" using LINQ like this:
var attachment = message.BodyParts.OfType<MimePart> ()
.FirstOrDefault (x => x.FileName == "test.txt");
// decode the content to a MemoryStream:
using (var memory = new MemoryStream ()) {
attachment.ContentObject.DecodeTo (memory);
}
// since the attachment is probably a TextPart
// (based on the file extension above), we can actually
// use a simpler approach:
var textPart = attachment as TextPart;
if (textPart != null) {
// decode the content and convert into a 'string'
var text = textPart.Text;
}
}
client.Disconnect (true);
}

Calling php script using C# (Unity)

I'm fairly new to both Unity and PHP, and I am currently working on a project where I can parse data from a MySQL database to Unity, using PHP.
I initially wanted to try and enable a method where the user can perhaps change the php script and enable it to choose a different table of data, however I was advised that it may be safer to list all variables within the php script and call it from Unity accordingly;
Display.php
$table = mysql_real_escape_string($_GET['table'], $db);
if ($table == "shoes") {
$query = "SELECT * FROM `shoes` ORDER by `price` ASC LIMIT 10";
elseif ($table == "sneakers") {
$query = "SELECT * FROM `sneakers` ORDER by `price` ASC LIMIT 10";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$num_results = mysql_num_rows($result);
for($i = 0; $i < $num_results; $i++)
{
$row = mysql_fetch_array($result);
echo $row['shopname'] . "\t" . $row['price'] . "\n";
}
I'm having trouble calling the php and choosing the table that I want to select, I am pretty new to this, so I apologise if this seems completely incompetent to you guys.
Here is the my Unity Script;
HSController.cs
void Start()
{
StartCoroutine(GetScores());
}
// remember to use StartCoroutine when calling this function!
IEnumerator PostScores(string name, int score)
{
string hash = Md5Sum(name + score + secretKey);
string post_url = addScoreURL + "name=" + WWW.EscapeURL(name) + "&score=" + score + "&hash=" + hash;
WWW hs_post = new WWW(post_url);
yield return hs_post; // Wait until the download is done
if (hs_post.error != null)
{
print("There was an error posting the high score: " + hs_post.error);
}
}
IEnumerator GetScores()
{
gameObject.guiText.text = "Loading...";
WWW hs_get = new WWW(highscoreURL);
yield return hs_get;
if (hs_get.error != null)
{
print("There was an error getting the high score: " + hs_get.error);
}
else
{
gameObject.guiText.text = hs_get.text; // this is a GUIText that will display the scores in game.
}
}
Any help or a point in the right direction would be great!
Kind Regards
Let me try to rewrite this into a working example:
C#
void Start() {
StartCoroutine(GetData());
}
IEnumerator GetData() {
gameObject.guiText.text = "Loading...";
WWW www = new WWW("http://yoururl.com/yourphp.php?table=shoes"); //GET data is sent via the URL
while(!www.isDone && string.IsNullOrEmpty(www.error)) {
gameObject.guiText.text = "Loading... " + www.Progress.ToString("0%"); //Show progress
yield return null;
}
if(string.IsNullOrEmpty(www.error)) gameObject.guiText.text = www.text;
else Debug.LogWarning(www.error);
}
PHP
<?php
//DB connection goes here
if ($_REQUEST['table'] === "shoes") { //I'm using REQUEST instead of GET, so it will work with both GET and POST
$query = "SELECT * FROM `shoes` ORDER by `price` ASC LIMIT 10";
} elseif ($_REQUEST['table'] === "sneakers") {
$query = "SELECT * FROM `sneakers` ORDER by `price` ASC LIMIT 10";
}
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['shopname'] . "\t" . $row['price'] . "\n";
}
?>
Hope this helps!

Categories