Its returning an empty string and I can't seem to figure out why, if you visit the page it outputs fine. (http://lgdev.site.nfoservers.com/getItems.php). I'm trying to get all the data, separate it by certain characters, then use the code in the game t operate it and sort it into the correct places. But like I said its returning an empty string instead of the data that's show on the webpage I gave above.
Game Code:
public void loadItems()
{
WWWForm form = new WWWForm();
WWW w = new WWW("http://lgdev.site.nfoservers.com/getItems.php", form);
StartCoroutine(loadItemsFunc(w));
}
IEnumerator loadItemsFunc(WWW w)
{
yield return w;
Debug.Log(w.text);
string[] tmpdata1 = w.text.Split(char.Parse("="));
foreach(string data in tmpdata1)
{
string[] tmpinfo = data.Split(char.Parse("~"));
GameObject tmpObj = Instantiate(weapon);
tmpObj.GetComponent<weapon>().name = tmpinfo[0];
tmpObj.GetComponent<weapon>().vitalisim = int.Parse(tmpinfo[1]);
tmpObj.GetComponent<weapon>().defence = int.Parse(tmpinfo[2]);
tmpObj.GetComponent<weapon>().strength = int.Parse(tmpinfo[3]);
string[] offsetInfo1 = tmpinfo[5].Split(char.Parse(";"));
foreach (string off in offsetInfo1)
{
string[] offset = off.Split(char.Parse(","));
tmpObj.GetComponent<weapon>().offsetsPos.Add(new Vector3(float.Parse(offset[0]), float.Parse(offset[1]), float.Parse(offset[2])));
tmpObj.GetComponent<weapon>().offetsRot.Add(new Vector3(float.Parse(offset[3]), float.Parse(offset[4]), float.Parse(offset[5])));
tmpObj.GetComponent<weapon>().offetsSize.Add(new Vector3(float.Parse(offset[6]), float.Parse(offset[7]), float.Parse(offset[8])));
}
string[] typeInfo = tmpinfo[4].Split(char.Parse(","));
if (tmpinfo[1] == "SwordnShield")
{
tmpObj.GetComponent<weapon>().anim = swordAndShieldAnimSet;
}
else if (tmpinfo[1] == "TwoHanded")
{
tmpObj.GetComponent<weapon>().anim = twoHandedAnimSet;
}
foreach (string prefab in tmpinfo[6].Split(char.Parse(",")))
{
tmpObj.GetComponent<weapon>().prefabs.Add(prefab);
}
}
}
PHP Code:
<?PHP
$con = mysql_connect("localhost","user","passs") or ("Cannot connect!" . mysql_error());
if (!$con)
die('Could not connect: ' . mysql_error());
mysql_select_db("lgdev_projectzed" , $con) or die ("could not load the database" . mysql_error());
$query = "SELECT * FROM `equipment`";
$check = mysql_query($query) or die(mysql_error()." ".$query);
if($check){
}
$numrows = mysql_num_rows($check);
$text = "";
while ($row = mysql_fetch_array($check, MYSQL_ASSOC)) {
$text = $text."".$row["name"]."~".$row["vitalism"]."~".$row["defence"]."~".$row["strength"]."~".$row["type"]."~".$row["offsets"]."~". $row["prefabs"] ."=";
}
die($text);
?>
First, check if it gives any error with:
Debug.Log(w.error); // place this before or after the other debug.log
Since the form that you submit is empty, there is some error..
So check how to setup your form:
https://docs.unity3d.com/ScriptReference/WWWForm.html
If you don't need to post anything in the form, can use the plain WWW
https://docs.unity3d.com/ScriptReference/WWW.html
Related
I'm trying to upload a photo from an android device to host using PHP and base 64, bitmap ; but it uploads two empty images (it uploads two times) can't figure out why, any help or alternative way?
I'm uploading the photo in a register layout so I tried just inserting the photo without anything else, and I tried using another hosting service but unfortunately, nothing worked.
the name of the empty photo is inserted in the database yet in the file manager it's an empty photo
the php code;
<?php
// array for JSON response
$response = array();
$user_image= $_POST['user_image'];
$user_name= $_POST['user_name'];
$user_email= $_POST['user_email'];
$user_un= $_POST['user_un'];
$user_pass= $_POST['user_pass'];
$servername = "...";
$username = "...";
$password = "...";
$dbname = "...";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
$ra=rand(0,20000);
$rn=rand(0,40000);
$rd=rand(0,60000);
$imgname = "pl".$ra.$rn.$rd.".jpeg";
$decoding=base64_decode("$user_image");
file_put_contents("images/".$imgname,$decoding);
$sql = "INSERT INTO Users (user_name,user_email,user_un,user_pass,user_image)
VALUES ('$user_name','$user_email','$user_un','$user_pass','$imgname')";
if ($conn->query($sql) === TRUE) {
$UserId = $conn->insert_id;
$response['dishs'] = array();
$hobbie['status'] = "ok";
$hobbie['result'] = "Welcome";
// push single dishinto final response array
array_push($response['dishs'],$hobbie);
// echoing JSON response
echo json_encode($response);
} else {
// echo "Error: " . $sql . "" . $conn->error;
$response['dishs'] = array();
// failed to insert row
$hobbie['status'] = "no";
$hobbie['result'] = "Error: " . $sql . "" . $conn->error;
array_push($response['dishs'],$hobbie);
// echo no users JSON
echo json_encode($response);
}
}
$conn->close();
?>
the kotlin code
these are defined in the head of the class
"class RegisterPage :Fragment() {
var encodImg = ""
var bitmap: Bitmap? = null
......
"
sending this to the host
"... val params = HashMap<String, String>()
params["user_image"] = encodImg
...
"
the way i choose the photo from gallery and encrypt
private fun startGallery() {
val galleryIntent = Intent(Intent.ACTION_GET_CONTENT)
galleryIntent.type = "image/*"
if (galleryIntent.resolveActivity(activity!!.packageManager) != null) {
startActivityForResult(galleryIntent, 1000)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, i: Intent?) {
super.onActivityResult(requestCode, resultCode, i)
if (resultCode == Activity.RESULT_OK) {
val uri: Uri? = i!!.data
change_profile_photo.setImageURI(uri)
manageImageFromUri(i.data!!)
} else {
Toast.makeText(activity, "Error", Toast.LENGTH_LONG).show()
}
}
private fun manageImageFromUri(imageUri: Uri) {
val baos = ByteArrayOutputStream()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Snackbar.make(view!!, "ERROR", Snackbar.LENGTH_LONG)
} else {
bitmap = MediaStore.Images.Media.getBitmap(activity?.contentResolver, imageUri)
bitmap!!.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
encodImg = Base64.encodeToString(b, Base64.DEFAULT)
}
}
}
PHP
dispdb.php
<?php
// Configuration
$hostname = '1(Ignore this)';
$username = '1(Ignore this)';
$password = '1(Ignore this)';
$database = '1(Ignore this)';
$secretKey = "1(Ignore this)";
try {
$dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password);
} catch(PDOException $e) {
echo '<h1>An error has occurred.</h1><pre>', $e->getMessage() ,'</pre>';
}
$realHash = md5($_GET['search'] . $secretKey);
if($realHash == $hash){
$sth = $dbh->query('SELECT * FROM `oidevstool` WHERE `id` =:search ORDER BY `id`');
$sth->setFetchMode(PDO::FETCH_ASSOC);
$result = $sth->fetchAll();
if(count($result) > 0) {
foreach($result as $r) {
echo $r['id'] . "/" . $r['title'] . "/" . $r['priority'] . "/" . $r['deadline'] . "/" . $r['comment'];
}
}
}
?>
database.cs
using UnityEngine;
using System.Collections;
public class database : MonoBehaviour {
private string secretKey = "1(Don't mid this)"; // Edit this value and make sure it's the same as the one stored on the server
public string addScoreURL = "1(Don't mid this)"; //be sure to add a ? to your url
public string highscoreURL = "http://example.com/dispdb.php?";
public string dataRetrieved;
public string search;
public string Md5Sum(string strToEncrypt)
{
System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
byte[] bytes = ue.GetBytes(strToEncrypt);
// encrypt bytes
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hashBytes = md5.ComputeHash(bytes);
// Convert the encrypted bytes back to a string (base 16)
string hashString = "";
for (int i = 0; i < hashBytes.Length; i++)
{
hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}
return hashString.PadLeft(32, '0');
}
// Get the scores from the MySQL DB to display in a GUIText.
// remember to use StartCoroutine when calling this function!
IEnumerator GetScores()
{
string hash = Md5Sum(search + secretKey);
string post_url = highscoreURL + "search=" + search + "&hash=" + hash;
WWW hs_post = new WWW(post_url);
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
{
dataRetrieved = hs_get.text;
}
}
void OnGUI()
{
GUI.Box(new Rect(0, 0, 800, 800), dataRetrieved);
search = GUI.TextField(new Rect(805, 0, 200, 30), search);
if(GUI.Button(new Rect(805, 35, 200, 30), "Search"))
{
StartCoroutine(GetScores());
}
}
}
i've looking ways to fix but i couldn't find any help for some reason this doesn't work whenever i pressed searched on Unity3D it didn't even show the "success", eventhough i made when hash are correct get data
any chance of someone going to help me?
that't will be very appreciated
Thankyou.
Best Regards
You are using a named placeholder :search in query() .
Use prepare() then either bind :search and execute() or use "lazy" binding by passing data into execute().
See PDO info for more
if($realHash = $hash){ should be if($realHash === $hash){
I've got a SQL table with 100 lines. Each line got a date.
I'd like to retrieve the info for a particular date.
Example :
With Flash, the user select the date 12/11/2014 and the AS3 code will display all the values (each columns of my table) that match this date.
In this example it will display "firstname : As de trefle, tome 1 : 10...etc" as it's the only entry that matches this date.
So far I've managed to select variables, in AS3, from users name, like that :
memberCombo.prompt = "Please select a user";
memberCombo.addItem( {label: "as de trefle" } );
memberCombo.addItem( {label: "kathy" } );
memberCombo.addItem( {label: "peter" } );
memberCombo.addEventListener(Event.CHANGE, checkComplete);
function checkComplete(evt:Event):void {
// Create A new URLVariables instance to store the variable
var myVariables:URLVariables = new URLVariables();
// Create a variable (e.g. candidate) to send
myVariables.username = evt.target.value;
// Create a new URLRequest instance sending data to "ascom01.php"
var myRequest:URLRequest = new URLRequest("http://www.example.com/sql_result.php");
// Send data using the POST method
myRequest.method = URLRequestMethod.POST;
// The data property of the request is set to the
// URLVariables instance (myVariables) to send to the PHP file.
// Note: myVariables stored the variable (e.g. candidate)
myRequest.data = myVariables;
// Create a new instance of the URLLoader class to work with.
// URLLoader.load( ) method should be used when we need the
// sent variables returned back to Flash ActionScript.
var myLoader:URLLoader = new URLLoader;
//specify dataFormat property of the URLLoader to be "VARIABLES"
//This ensure that the variables loaded into Flash with the same variable names
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
//Load the PHP file by using URLRequest
myLoader.load(myRequest);
//Listen when the loading of data COMPLETE
//Call the loadComplete function when the loading COMPLETE
myLoader.addEventListener(Event.COMPLETE, loadComplete);
}
// This is the function that display the data returned back from PHP file
function loadComplete(evt:Event):void {
//Display the value with variable name "totalItem"
total_txt.text = evt.target.data.totalItem
//Get the value (string) with variable name "phpConfirm"
var myResult:String = evt.target.data.phpConfirm;
//Split the string into an Array
var myArray:Array = myResult.split("|");
//output_txt.text = "The number of items are: " + myArray.length;
var finalString = "";
var i:int;
for (i = 0; i < myArray.length; i++) {
finalString = finalString + myArray[i] + "<br>";
}
output_txt.htmlText = finalString;
}
And in my sql_result.php:
<?php
$username = $_POST['username'];
// create connection
$connection = mysql_connect("****.perso", "root", "root") or die ("Couldn't connect to the server.");
// select database
$db = mysql_select_db("dbase", $connection) or die ("Couldn't select database.");
// create SQL
$sql = "SELECT domain FROM d_table where username = '$username'";
// execute SQL query and get result
$sql_result = mysql_query($sql, $connection) or die ("Couldn't execute query.");
// get number of rows in $result.
$num = mysql_numrows($sql_result);
$phpConfirm = "";
$counter = 0;
while ($row = mysql_fetch_array($sql_result)) {
$domain = $row["domain"];
if ($counter == 0) {
$phpConfirm .= $domain;
} else {
// Use a item limiter "|" to seperate the records
$phpConfirm .= "|" . $domain;
}
$counter++;
}
echo "phpConfirm=" . $phpConfirm . "&totalItem=" . $num;
// free resources and close connection
mysql_free_result($sql_result);
mysql_close($connection);
?>
How can I retrieve the variables with the date and not the username ?
And, more complex, how can I use both ? (example : I choose the date AND the username "John" and it shows me all the variables of my table where the date and the username matches ?
Thank you for your help,
EDIT
So, I've changed in my AS3 code the labels by these :
memberCombo.prompt = "Please select a date";
memberCombo.addItem( {label: "2015-06-23" } );
memberCombo.addItem( {label: "06/23/2015" } );
memberCombo.addItem( {label: "23-06-2015" } );
and in my php code :
I've changed
$username= $_POST['username'];
by
$date = $_POST['date'];
and
$sql = "SELECT domain FROM d_table where username = '$username'";
by
$sql = "SELECT domain FROM d_table where date = '$date'";
But it seems that my flash app doesn't find any "domain" with this date.
No error. It just doesn't find anything.
Any idea why ?
Already tearing my hairs out for a couple of days. There is not much left of them ;-)
I am experiencing a strange problem when I want to bind a service to a button or something else:
files:
- CDPC.php
<?php
require_once ('VOcdpc.php');
class CDPC {
var $username = "root";
var $password = "";
var $server = "localhost";
var $port = "3306";
var $databasename = "xoffercommon";
var $tablename = "tblcity";
var $connection;
public function __construct() {
$this->connection = mysqli_connect(
$this->server,
$this->username,
$this->password,
$this->databasename,
$this->port
);
mysqli_set_charset($this->connection,'utf8');
$this->throwExceptionOnError($this->connection);
}
public function getCDPC($cityID) {
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xoffercommon", $con);
$cdpc_Id = new Vocdpc();
$cdpc_Id->id_cdpc = 1;
$cdpc_Id->city_Id=$cityID;
$result_prov = mysql_query("SELECT tblProvence_Id FROM tblCity WHERE Id = " . $cityID);
$row = mysql_fetch_array($result_prov);
$cdpc_Id->provence_Id=intval($row['tblProvence_Id']);
$result_dist = mysql_query("SELECT tblDistrict_Id FROM tblProvence WHERE Id = " . $cdpc_Id->provence_Id);
$row = mysql_fetch_array($result_dist);
$cdpc_Id->district_Id=intval($row['tblDistrict_Id']);
$result_coun = mysql_query("SELECT tblCountry_Id FROM tblDistrict WHERE Id = " . $cdpc_Id->district_Id);
$row = mysql_fetch_array($result_coun);
$cdpc_Id->country_Id=intval($row['tblCountry_Id']);
return $cdpc_Id;
mysql_close($con);
}
private function throwExceptionOnError($link = null) {
if($link == null) {
$link = $this->connection;
}
if(mysqli_error($link)) {
$msg = mysqli_errno($link) . ": " . mysqli_error($link);
throw new Exception('MySQL Error - '. $msg);
}
}
}
?>
VOcpdc.php
<?php
class VOcdpc
{
public $id_cdpc;
public $country_Id;
public $district_Id;
public $provence_Id;
public $city_Id;
// explicit actionscript class
var $_explicitType = "Vocdpc";
}
?>
In flex builder
I can add the services to the Data Services panel but I have two strange things:
1) when I want to configure the return type he doesn't let me create a new ValueObject type, I only get the bottom datagrid which states: Properties returned by the operation: Property: country_Id, provence_Id, city_Id, id_cdpc, district_Id with the related values on the right side. Why can't I create a new data type on the top?
2) When I accept this and want to add the service call to a button (drag&drop) I get the following error: Error occurred while generating code. Make sure that there are no compiler eroors and try again after reopening the file. Componentn type services.cdpc.CDPC not found...
(ps: When I perform a Test Operation everything seems to be ok, I get the expected output values)
this is the class included in the main cdpc.php file, the post drops it apparently, so here is the VOcpdc file:
// explicit actionscript class
var $_explicitType = "Vocdpc";
}
?>
I have a nice page including system here is the code for it
if(isset($HTTP_GET_VARS['mod']))
{
$page = $HTTP_GET_VARS['mod'];
}
else
{
$page = 'home';
}
switch($page)
{
case 'home':
require('home.php');
break;
default:
echo('Error: There is no file on this server with that name');
}
}
I am trying to get the case, require from a DB called pages there are 2 fields Name, Link i am trying to get all of the results from the table so it will display the pages
It's not particularly clear from your question, but my reading of it is that you want a way to check any value of $page against a link value in a db table (pages?), without having to write all possible values in to your switch statement,
If my understanding is correct, then the below is a quick-and-dirty function which should let you do this. In a live, heavily-trafficed environment you'd obviously need to build in caching so every page load doesn't hit the db, and strong input validation, neither of which are in the demo below, but this should at least give you an idea of where to go next.
Common library file:
/**
* Given a page name, see if we have an associated
* link in the db.
* If so, return the link value, else false
*/
function getTemplate($page)
{
// Check db to see if we have a link for this page
// On heavy-traffic sites, this should be cached out
$query = sprintf("SELECT link FROM pages WHERE name = '%s'",
mysql_real_escape_string($page));
$result = mysql_query($query, $db_cnx);
// Have we any results?
if (mysql_num_rows($result) > 0)
{
// Assumption: 'name' is unique in the db
$row = mysql_fetch_assoc($result);
return $row['link'];
}
else
{
return false;
}
}
Header.php:
include('common.lib.php');
if(isset($HTTP_GET_VARS['mod']))
{
$page = $HTTP_GET_VARS['mod'];
}
else
{
$page = 'home';
}
// Check whether our page has a link in the db
$template = get_template($page);
if($template)
{
require( $template );
}
else
{
// Got false back from get_template, no link found
echo('Error: There is no file on this server with that name');
}
$server_db = "YOUR_SERVER_DB";
$user_db = "YOUR_USER_DB";
$password_db = "YOUR_PASSWORD_DB";
$db_name = "YOUR_DB_NAME";
$table = "YOUR_TABLE_NAME";
$link = mysql_connect($server_db,$user_db,$password_db);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_name);
$sql = sprintf("select Name, Link from %s",$table);
$rs = mysql_query($sql,$link);
while($row = mysql_fetch_assoc($rs)) {
echo "<a href='".$row['Link']."'>".$row['Name']."</a>";
}
mysql_free_result($rs);
mysql_close($link);