download values of sql table for offline reuse - php

I've got a Flash app that calls an online php file in order to read some values of my SQL table.
So I've got a line like this in my AS3 code:
var urlReq:URLRequest = new URLRequest ("http://www.****.com/sql_result.php");
And this in my php :
$connection = mysql_connect("mysql***.perso", "test", "password") or die ("Couldn't connect to the server.");
Problem : if the user is offline he can't access the values.
Is there way to download the SQL table with AS3 code (when the user have internet) in order to access it offline.
Like :
function onConnection(e:Event = null):void{
if(monitor.available)
{
trace("You are connected to the internet");
read_php_online();
}
else
{
trace("You are not connected to the internet");
read_php_offline();
}
monitor.stop();
}
function read_php_offline():void{
var urlReq:URLRequest = new URLRequest ("local/sql_result_offline.php");
..
..
}
And what should have sql_result_offline.php in order to access an offline SQL Table ?
$connection = mysql_connect("LOCAL", "user", "password");
Thank you,

For FLASH :
To save data locally with flash, you can use one of 3 manners : the Flash Player cache, a SharedObject, or a FileReference object. And for your local file, forget PHP and MySQL because we are speaking only about the data that you got ( json, xml, txt, ... ).
- Flash Player cache :
You should know that by default, flash player put a local copy of your file in its cache. You can use this local copy as an offline source of your data, but here don't forget that flash player didn't save the last version of your remote file but the first one and that http://www.example.com/data.php is different from http://www.example.com/data.php?123 even if it's the same file ! For more details about that, take a look on my answer of this question.
- SharedObject :
I don't know the size of your loaded data, but as Adobe said about SharedObject :
... is used to read and store limited amounts of data on a user's computer ...
I think that is not used for large files and it's not recommended to store files but some simple data. Of course, as a cookie for the browser, SharedOject needs user's authorization to write data to the hard drive, and user can delete it at any time.
- FileReference :
I think this is the best manner to do what you are looking for. You should know that to save a file using FileReference, your user is invited to select a file for saving data and reading it in a second time. So if you don't want any user's interaction with your application, forget this manner.
FileReference using example :
var local_file_name:String = 'local.data',
file:FileReference = new FileReference(),
local_file_filter:FileFilter = new FileFilter('local data file', '*.data'),
remote_data_url:String = 'http://www.example.com/data.php',
url_request:URLRequest,
url_loader:URLLoader,
connected:Boolean = true;
if(connected){
get_remote_data();
} else {
get_local_data();
}
function get_remote_data(): void {
//we use a param to be sure that we have always the last version of our file
url_request = new URLRequest(remote_data_url + ('?' + new Date().getTime()));
url_loader = new URLLoader();
url_loader.addEventListener(Event.COMPLETE, on_data_loaded);
url_loader.load(url_request);
}
function get_local_data(): void {
// show the select dialog to the user to select the local data file
file.browse([local_file_filter]);
file.addEventListener(Event.SELECT, on_file_selected);
}
function on_data_loaded(e:Event): void {
var data:String = e.target.data;
// if the remote data is successfully loaded, save it on a local file
if(connected){
// show the save dialog and save data to a local file
file.save(data, local_file_name);
}
// use your loaded data
trace(data);
}
function on_file_selected(e:Event): void {
file.addEventListener(Event.COMPLETE, on_data_loaded);
file.load();
}
This code will show every time a save dialog to the user, of course, it's just a sample, you have to adapt it to your needs ...
EDIT
For AIR :
With AIR we don't need a FileReference object, instead we use File and a FileStream object to save data :
// for example, our local file will be saved in the same dir of our AIR app
var file:File = new File( File.applicationDirectory.resolvePath('local.data').nativePath ),
remote_data_url:String = 'http://www.example.com/data.php',
data_url:String = remote_data_url,
url_request:URLRequest,
url_loader:URLLoader,
connected:Boolean = true;
if(!connected){
// if we are not connected, we use the path of the local file
data_url = file.nativePath;
}
load_data();
function load_data(): void {
url_request = new URLRequest(data_url);
url_loader = new URLLoader();
url_loader.addEventListener(Event.COMPLETE, on_data_loaded);
url_loader.load(url_request);
}
function on_data_loaded(e:Event): void {
var data:String = e.target.data;
if(connected){
// save data to the local file
var file_stream:FileStream = new FileStream();
file_stream.open(file, FileMode.WRITE);
file_stream.writeUTFBytes(data);
file_stream.close();
}
trace(data);
}
Hope that can help.

you have a flash swf, mobile app or air app?
Storing local data
you can use file as database (like csv), for mobile and air you can use local SQLite database.
if you have native desktop app - it is possible to use mysql, via native process or native extension but it is not so easy..
edit:
Working with local SQL databases in AIR [+] you can keep your data safe- with encryption, a password at startup and etc. [-] it will require a lot more of code (create database after install, sync regularly, get data from local database if no internet conn.) mysql and sqlite have some differences also (like "insert or update" statement for sqlite)

Related

Loading PHP URL in Flash AS3

I am working on an online game in Flash AS3 and utilizing a PHP server with mySQL database. I am manipulating the data in mySQL database using PHP and when I request the PHP file in a browser straightly from 'localhost/php/file.php', the database changes perfectly. I have the following AS3 code:
public function getSite(string):Boolean{
var phpVars:URLVariables = new URLVariables();
var t:Boolean = false;
/*
we use the URLRequest method to get the address of our php file and attach the php vars.
*/
var urlRequest:URLRequest = new URLRequest(string);
/*
the POST method is used here so we can use php's $_POST function in order to recieve our php variables.
*/
urlRequest.method = URLRequestMethod.POST;
/*
this attaches our php variables to the url request
*/
urlRequest.data = phpVars;
/*
we use the URLLoader class to send the request URLVariables to the php file
*/
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlLoader.addEventListener(Event.COMPLETE, check(t));
t = check(t);
/*
runs the function once the php file has spoken to flash
*/
/*
we send the request to the php file
*/
urlLoader.load(urlRequest)
return t;
}
function check(t:Boolean):Function{
return function (event:Event):Boolean{
trace(event.target.data.checkResult);
if(event.target.data.checkResult == "Good"){
t = true;
} else {
t = false;
}
return t;
}
}
Now from here, my "trace" shows that the URL is loaded and the output is "Good", however the database values does not change. This is the PHP file:
<?php
/*
connect to our database
*/
include_once "connect.php";
$sql = "UPDATE accounts SET PlayersOnline = accounts.PlayersOnline + 1";
$query = mysql_query($sql) or exit("checkResult=Bad");
exit("checkResult=Good");
?>
When I go to 'localhost/php/gameSearch.php' in my web browser the database changes, and I am wondering what the problem is.
You have a "caching" problem. In other words, the result of the already requested URL is cached to reduce latency and access times, and what you've represented is the cached copy of the output and not a fresh output resulting from the execution of the instructions on behalf of the server.
To overcome the issue, you could've pushed a no-cache header to the requestHeaders property on your "request" object (the property is of type URLRequestHeader). However, the runtime looks to be ignorant on the header and it always provides the cached copy!
To overcome that issue, however, you need to fool the runtime as if you are requesting a new URL every time by appending a dummy random-valued variable:
getSite("localhost/php/file.php?r="+Math.random());
And regarding your specific provided code; The URLLoader works asynchronously, that's why you register a "on complete" listener! The t = check(t); statement induces you're attempting to "check" the result while it may not be ready by then! You should check it when/after the listener triggered. In addition to the fact that the assignment is syntactically inappropriate (assigning a Function to a Boolean!) and reconsider the logic of the check function!
And in the PHP code, as others have suggested, ultimatly don't use the deprecated mysql_query function and use a more appropriate API.

Getting a HeartBeat from a C# Application and Posting it To Website

I've got a Minecraft Software written in C# that I want to send a heartbeat to my site. I've got the way to send the beat already written.
if (Server.Uri == null) return;
string uri = "http://GemsCraft.comli.com/Heartbeat.php";
// create a request
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
// turn request string into a byte stream
byte[] postBytes = Encoding.ASCII.GetBytes(string.Format("ServerName={0}&Url={1}&Players={2}&MaxPlayers={3}&Uptime={4}",
Uri.EscapeDataString(ConfigKey.ServerName.GetString()),
Server.Uri,
Server.Players.Length,
ConfigKey.MaxPlayers.GetInt(),
DateTime.UtcNow.Subtract(Server.StartTime).TotalMinutes));
request.ContentType = "application/x-www-form-urlencoded";
request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
request.ContentLength = postBytes.Length;
request.Timeout = 5000;
Stream requestStream = request.GetRequestStream();
// send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Flush();
requestStream.Close();
/* try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Logger.LogToConsole(new StreamReader(response.GetResponseStream()).ReadToEnd());
Logger.LogToConsole(response.StatusCode + "\n");
}
catch (Exception ex)
{
Logger.LogToConsole("" + ex);
}*/
}
Now, I want to be able to retrieve the heartbeat in PHP, upload it to the SQL database, and then display each user's server in a table that will be displayed on the webpage
How do I do this?
portforwardpodcast's answer isn't very well-suited for your purposes, here's a process for you to ponder
Server accesses the following page: heartbeat.php?port=25565&maxplayers=25&players=2&name=Cheese_Pizza_Palace
Your PHP script will then do the following...
Go through each value, making sure they're all the types you want them to be (integers/strings)
Connect to the database
Update the server in the database if it already exists, create it if it doesn't
Return some value so the server knows that it completed successfully.
And to display the servers
Fetch all 'active' servers
Loop through them and display each one.
Things you'll need to figure out:
How to determine uptime
How to determine "active" servers
How to update/create MySQL entries
How to (properly) connect to a database. I would suggest using PDO since you're using PHP. It's a bit difficult to learn, but it's much more secure than writing the queries directly.
How to loop through all the GET variables.
Good hunting!
I would create a simple php page accept a get variable. something like www.site.com/beat.php?lasttime=123456&serverid=1 where the number us the unix timestamp. Then you need to re-work your c# to do a simple get request on a website. Finally your php should insert into a mysql table with a column for id, timestamp, server_id etc.
First you need to pull the data from the request. The $_REQUEST variable in php is nice because it works for both GET and POST:
http://php.net/manual/en/reserved.variables.request.php
Start out by var_dump or echo the fields you want. Once you can get the needed data into variables you are done with the first part. For the next part you need to create a database and table in MySQL. The best tool for this is phpmyadmin. If you have a host like godaddy (or some others) you can get at this from the control panel. If not you may need to install upload the phpmyadmin files yourself. It's a pretty simple tool to use:
http://www.youtube.com/watch?v=xxQSFHADUIY
Once your database has the correct columns, you need to insert the data from your php file. This page should help:
http://www.w3schools.com/php/php_mysql_insert.asp

Flex and PHP Connection

I am working on a project involving a PHP connection, the UI is developed using flash builder, I have Combo Box and Text Input for users to pick some items and at the same time users can input their details on the Text Input. The app is not generating anything up till now. I need to send data to PHP for PHP to look up into its folder containing some images. I used folder instead of database, the output should be sent back to Flex for it to be saved into another folder and I also want a copy to be saved inside another folder in PHP. Please is there anyone that could be of help?
These are some of the codes used:
public function Drop2_disabled(event:Event):void{
love=="orange"&&"pawpaw"&&"maize"; hate=="rice"&&"maize"&&"starch";
if((Drop2.selectedItem=="orange"||"pawpaw"||"maize")&&
(Drop3.selectedItem=="rice"||"maize"||"starch"))
ValueCommit="{foodVO.love}"
}
was now used under the ComboBox to bind foodVO to variable love, this was repeated for the text Input also. My foodVO is an action script file. foodVO was then mapped to my foodVO.Php using Zend server.
The PHP will then use the data sent from the remote object to look up into his own folder to read the images and then send it back to flex.
(services-config.xml)
These are some of the PHP script
<?php
class foodVO
{
public $maize;
public $rice;
public $pawpaw;
public $starch;
public $orange;
public function _construct()
{
$maize = $_GET["maize"];
$rice = $_GET["rice"];
$orange = $_GET["orange"];
$pawpaw = $_GET["pawpaw"];
$this->maize = "";
$this->orange = "";
$this->pawpaw = "";
$this->starch = "";
}
}
?><?php
include 'Zend/Amf/Server.php';
include './food.php/services/foodService.php';
// Initialize AMF Server
$server = new Zend_Amf_Server();
$server->setClass("foodService");
$server->setProduction($amf->production);
$server->setClassMap('foodVO', 'foodVO');
// Handle request
echo $server->handle();
?>
The foodservice.php contains my Imagick operations.
Please I need help?
Thanks.
I don't know how you achieved the connection but in order to send data back and forward between PHP and Flex there is the ActionScript Message Format extension. There are also libraries that you can use such as AmfPHP. Zend also has classes for this - Zend Amf.

Less painful way to migrate from MySQL to a local single file implementation of the database (flash & AS3)

i have a database in MySQL who i query from a php script. Now i want to run the same aplication but in local (without the php script, the mysql and whitout the server). I develop the IDE of the new app using flash (AS3), now the think is that i need to migrate the data base too.
I was thinking using SQLite wich is great because it use the same commands that mysql and is local, but i really dont know how to make querys from AS3 to sqlite whitout using php. I was also thinking to develop a simple script who read my actual data base (mysql) and parse all the data to a new XML file who then i can read from the new IDE develop in flash, the problem is, that in this way i have to write all the code for the querys, i mean, when i use php+mysql and i need all the data WHERE reef=2 i just make a simple query, but with the new hypothetical schema flash+xml to make a simple query like that i have to write a lot of code if you know what i mean.
So, if you have any ideas let me know, remember that im developing in AS3 with FLASH. Thanks!
adobe air is the only way you can achive this on a local computer.
here some snippets:
// connect to SQLite
var file:File = preferences.resolvePath("data.db");
var sqlConnection:SQLConnection = new SQLConnection();
sqlConnection.open(file);
// prepare statement to find photos in album
var stmtFindPhotosToAlbum:SQLStatement = new SQLStatement();
stmtFindPhotosToAlbum.sqlConnection = sqlConnection;
stmtFindPhotosToAlbum.text = "SELECT * FROM photos WHERE album_id = :album_id";
// execute query
stmtFindPhotosToAlbum.parameters[":album_id"] = 'albumId';
stmtFindPhotosToAlbum.execute();
// get result
var photos:Array = stmtFindPhotosToAlbum.getResult().data;
var photoVos:Array = [];
if (photos != null && photos.length > 0)
{
for(var i:int = 0;i<photos.length;i++)
{
// ...
}
}

AS3 and mySQL or XML: Saving user votes on server from a flash movie

A project of mine involves a flash movie (.swf) in a webpage, where the user has to pick from a number of items, and has the option to thumbs up or thumbs down (vote on) each item.
So far I have gotten this to work during each run of the application, as it is currently loading the data from an XML file - and the data is still static at the moment.
I need to persist these votes on the server using a database (mySQL), such that when the page is reloaded, the votes aren&apos;t forgotten.
Has anyone done this sort of thing before?
The two mains methods that I have found on the &apos;net are
either direct communication between AS3 and the SQL using some sort of framework, or
passing the SQL query to a PHP file, which then executes the SQL query and returns the SQL to AS3.
Which of these methods is the better option?
For the latter method (involving PHP), I have been able to find resources on how to acheive this when attempting to retrieve information from the database (i.e. a read operation), but not when attempting to send information to the database (i.e. a write operation, which is needed when the users vote). How is this done?
Thank you!
Edit: Implemented solution
Somewhere in the PHP file:
if ($action == "vote")
{
$id = $_POST['id'];
$upvotes = $_POST['upvotes'];
$query = "UPDATE `thetable` SET `upvotes` = '$upvotes' WHERE `thetable`.`id` = '$id' LIMIT 1 ;";
$result = mysql_query($query);
}
Somewhere in the ActionsScript:
public function writeToDb(action:String)
{
var loader:URLLoader = new URLLoader();
var postVars:URLVariables = new URLVariables();
var postReq:URLRequest = new URLRequest();
postVars.action = action;
postVars.id = id;
postVars.upvotes = upvotes;
postReq.url = <NAME_OF_PHP_FILE>;
postReq.method = URLRequestMethod.POST;
postReq.data = postVars;
loader.load(postReq);
loader.addEventListener(Event.COMPLETE, onWriteToDbComplete);
}
I am not aware of any framework that supports method-1.
I would use method-2 - but instead of making the query within Flash and passing it to PHP, I would rather pass the related data and construct the query in PHP itself. This is safer because it is less susceptible to SQL injection attacks.
This answer has an example of sending data from flash to the server - it talks about ASP, but the method is same for PHP (or any technology) - just change the URL.
Within the php code, you can read the sent data from the post $_POST (or $_GET) variable.
$something = $_POST["something"]
Many different options:
AMFPHP - binary messaging format between PHP and Actionscript/Flash.
LoadVars - for POSTing and GETing values to a PHP script.
JSON - Using the AS3Corelib you can post JSON formatted data to your web site (just like an AJAX script does).

Categories