Retrieving Information from MySQL via PHP to AS3 - php

I am currently doing a tutorial which was found on TutsPlus.
This tutorial was to save information from AS3 to MySQL via PHP and then retrieve this information.
So far, it works. I Can enter a username and score, which saves to the database. There is one problem though, I would like to be able to display ALL the names and scores in a table, instead of having to search for a name and then finding the score for that specific user.
The code in which the information is saved (which works), is below.
package {
import flash.display.*;
import flash.events.*;
import flash.net.*;
public class register extends MovieClip {
public function register ():void {
register_button.buttonMode = true;
register_button.addEventListener(MouseEvent.MOUSE_DOWN, checkForm);
username_text.text = "";
userbio_text.text = "";
}
public function checkForm (e:MouseEvent):void {
if (username_text.text != "" && userbio_text.text != "") {
sendForm();
} else {
result_text.text = "PLEASE ENTER A NAME";
}
}
public function sendForm ():void {
/*
we use the URLVariables class to store our php variables
*/
var phpVars:URLVariables = new URLVariables();
phpVars.username = username_text.text;
phpVars.userbio = userbio_text.text;
/*
we use the URLRequest method to get the address of our php file and attach the php vars.
*/
var urlRequest:URLRequest = new URLRequest("localhost/php/register.php");
/*
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;
/*
runs the function once the php file has spoken to flash
*/
urlLoader.addEventListener(Event.COMPLETE, showResult);
/*
we send the request to the php file
*/
urlLoader.load(urlRequest);
}
/*
function to show result
*/
public function showResult (e:Event):void {
result_text.text = "" + e.target.data.result_message;
}
}
}
From here, I can go to another application and search the users name, and then displays that users score. Code below:
package actions {
import flash.display.MovieClip;
import flash.events.*;
import flash.net.*;
import flash.text.*;
public class main extends MovieClip {
public function main ():void {
submit_button.buttonMode = true;
submit_button.addEventListener(MouseEvent.MOUSE_DOWN, checkLogin);
username.text = "";
}
public function checkLogin (e:MouseEvent):void {
if (username.text == "") {
username.text = "Enter your username";
}
else {
processLogin();
}
}
public function processLogin ():void {
var phpVars:URLVariables = new URLVariables();
var phpFileRequest:URLRequest = new URLRequest("http://xx.xx.xx.uk/~bf93fv/Source%202/php/controlpanel.php");
phpFileRequest.method = URLRequestMethod.POST;
phpFileRequest.data = phpVars;
var phpLoader:URLLoader = new URLLoader();
phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
phpLoader.addEventListener(Event.COMPLETE, showResult);
phpVars.systemCall = "checkLogin";
phpVars.username = username.text;
phpLoader.load(phpFileRequest);
}
public function showResult (event:Event):void {
result_text.autoSize = TextFieldAutoSize.LEFT;
result_text.text = "" + event.target.data.systemResult;
}
}
}
The controlpanel.php file, which displays the username and score individually is below:
<?php
include_once "connect.php";
$username = $_POST['username'];
if ($_POST['systemCall'] == "checkLogin") {
$sql = "SELECT * FROM users WHERE username='$username'";
$query = mysql_query($sql);
$login_counter = mysql_num_rows($query);
if ($login_counter > 0) {
while ($data = mysql_fetch_array($query)) {
$userbio = $data["user_bio"];
print "systemResult=$username Scored $userbio";
}
}
else {
print "systemResult=The login details dont match our records.";
}
}
?>
Does anybody know any easy way in order to view ALL the information from the database into a table?

There are few things you might want to improve in your PHP code (your AS3 is better).
Use PDO instead of the functions that work with particular DBMS. The reason to this is that it is portable (to an extend). Say, if you wanted to ever move the database from MySQL to Postgres, you'd had to rewrite less of your code, then you would have to otherwise. PDO also provides some means of sanitizing the input. It's not bullet proof - still better then nothing. PDO is considered the "good practice", so you would learn to write the good code right away instead of making that journey from writing newby-style code at first and then discovering how to actually do it properly. It might be just a little bit more verbose if you are thinking about a very primitive task such as a single select, but as soon as your task becomes just a little bit more complex it becomes all worth the time.
In your SQL queries make a general rule never to use select *, unless for testing / debugging. That's sort of laziness that in the end will cost you a lot of problems. By doing so you will make it very difficult to maintain your code later, effectively transforming it into "write once - run away" kind of thing. Again, as a simple proof of concept it is OK, - long-term solution - bad. If you are still blur on what I'm trying to say: list all column names explicitly.
Using include / require and their _once family is a bad idea as a long-term solution. Again, OK for a simple test - bad in the long run. Good programs are written in functions / classes and use __autoload() or a framework that uses the ability to load classes automatically. This makes larger applications more manageable, easier to navigate and understand then the web of includes.
You must sanitize input from the user of your web application, that is don't do $_POST['key']. At least write the function that will both check that the key exists and that it is of an expected format.
Now, your actual problem, sending the data.
You can just send the raw SQL output you get in PHP - will spare your server the problem of re-encoding all of it. Works in the very simple cases, but it becomes more complex with more complex tasks. This is also uncommon to do, so you will find that people will not know how to handle that. (No technical restriction, it is just really a historical artefact).
There are a bunch of popular formats that can be digested by variety of applications, not necessary Flash. Those include XML, JSON, Protobuf. There are also some more particular to PHP like the one produced from serialize(). I'd urge you to stick to JSON if you go down this route. XML might be a more mature technology, but JSON has a benefit of the basic type system built in (while in XML it is yet another layer on top of it, which is, beside other things is not implemented in Flash - I'm talking about XSL).
There's AMF (ActionScript Message Format) - it is ideal for Flash. PHP also knows very well how to produce it (there are several popular implementations out there). This format is a lot more compact compared to JSON or XML. It has more expressive power (can describe circular dependencies, many-to-many relationships, has a procedure for introducing custom types, custom [de]serialization routines). It is also self-describing, unless you used custom serialization routine. This is the best option if you aren't planning on moving your application to JavaScript later, because JavaScript has problems consuming binary data. Parsing this format would not be possible there.
Protobuf is a viable option too. This is a data exchange format designed by Google. It is similar in spirit to AMF, however it may not be self-describing. It relies on the application to know how to produced custom objects from it. It has, however, a form, that can be parsed in JavaScript (although you'd lose the the compactness benefit).
Your ActionScript code: If you opt for AMF, you'd need to look into NetConnection class. I'd advise you to take a look in AMFPHP project - it also has examples. Alternatively, Zend Framework has Zend_Amf library to be used for that purpose. But using the entire framework may be overwhelming at start.
If you go with XML - then there's a built-in XML class, there are millions of examples on the web on how to use it.
If you go with JSON, then since not so long ago there's a built-in class for that too. But before there was one, there were several libraries to parse it.
There used to be a project on GoogleCode for Protobuf support in Flash, but it required quite a bit of acquittance and manual labour to get going.
Finally, index of things mentioned here:
http://php.net/manual/en/book.pdo.php - PDO
http://php.net/manual/en/function.json-encode.php - JSON in PHP
http://php.net/manual/en/book.dom.php - XML in PHP (There is no agreement on which XML library is better if PHP is considered. I'd probably stick to this, but ymmv).
http://www.silexlabs.org/amfphp/ - AMF in PHP
http://framework.zend.com/manual/1.12/en/zend.amf.html Zend_Amf library
http://code.google.com/p/protobuf-actionscript3/ Protobuf in ActionScript
https://github.com/drslump/Protobuf-PHP PHP Protobuf (sorry, never used this one, but looks fine)
http://www.blooddy.by/en/crypto/ for older versions of Flash player - this library has the best JSON decoder I know of.

The best way is (I think) to use XML.
On the PHP side, the script output an XML document with all the users :
$sql = "SELECT * FROM users "; // add order statement if needed
$query = mysql_query($sql);
$login_counter = mysql_num_rows($query);
$xml = array('<?xml version="1.0" encoding="UTF-8"?><users>');
if ($login_counter > 0) {
while ($data = mysql_fetch_array($query)) {
$xml[] = '<user name="'.$data['username'].'" bio="'.$data["user_bio"].'" />';
}
}
else {
// do nothing
// you will handle it on the flash side by checking the length of user nodes list
}
$xml[] = '</users>';
header('Content-Type:text/xml');
die(implode('', $xml));
This will output an XML document :
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user name="..." bio="..." />
<user name="..." bio="..." />
[...]
</users>
(There are class on PHP like SimpleXML to deal with XML in a cleaner way)
AS Side :
You can easily browse / display the data on the flash side with the help of the XML / XMLList class
Just adapt the URLLoaderDataFormat to TEXT and convert the data to XML in the complete event handler :
var xml:XML = new XML(event.target.data);
Then iterate the user elements to display them :
var users:XMLList = xml.user;
var user:XML;
for (user in users) {
trace('name->' + user.attribute('name') );
trace('bio->' + user.attribute('bio') );
}

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.

Netsuite SuiteTalk - requesting list of invoices for a customer via PHP

I'm using the Netsuite PHP Toolkit to try to obtain a list of invoices for a customer. I can do the call (using a TransactionSearch) with no problem, but I'm struggling to understand how I'm supposed to get all details for an invoice - i.e. the invoice "header" details (e.g. grand total, currency, main menu line etc) as well as details for each line item (net value, taxable value, item etc).
I have tried a couple of approaches:
TransactionSearchAdvanced, with return columns specified and returnSearchColumns preference set to "false". This gives back all the separate lines (woo!) but things like currency and term aren't expanded out - you just get internalId specified and not the actual text (or the symbol). Also, with TSA, do you really have to specify every column you want? i.e. is the default really just an empty set of fields? Isn't there a way of just saying "give me all the details for all lines of each invoice?
TransactionSearch, with returnSearchColumns preference set to "true". This gives a list of single Invoice type records, with all the currency and term stuff correctly populated, but frustratingly, none of the individual line items. It's more of a summary.
So I am left with a couple of options, neither of which are very palatable, namely:
Do both calls for all invoices and combine the data. These searches take a long time (performance is another bugbear for me, so I really don't want to do this.
or
Figure out a way of requesting the data for terms, currency etc and also a way of obtaining invoice lines.
I have no idea how you're supposed to do this, and can't find anything on the internet about it. This is one of the worst interfaces I've used (and I've used some pretty bad ones).
Any help would be hugely appreciated.
Just like you I started out trying to do things with the Web Services API (aka SuiteTalk). Mostly it was an exercise in frustration because eventually what I found out was that I plain couldn't do what I wanted with them. That and the performance was pretty bad, which would have killed my project even if it had worked properly.
Like Faz, I've found it much easier and faster to use a combination of RESTlets and Saved Searches than deal with the web services framework.
Basically break your problem down into these parts:
Saved Search that returns the results that you want (keep track of the internal ID you'll need it later)
RESTlet it's just a Javascript file that defines the function you will use to return the results from the search
Client code to call the RESTlet and get the results.
Part I:
So the saved search is pretty straightforward. I'm going to assume you can make that happen and also that you can actually get all the fields you want in one place. That hasn't always been the case in my experience.
Part II:
The RESTlet involves a lot more steps even though it's really a very simple thing. What makes it complicated is getting it uploaded and deployed on your NetSuite site. If you don't already have the NetSuite IDE installed I highly recommend it if only to make deploying the scripts a little easier. The autocompletion and tooltips are extremely useful as well.
For instance here is code I use to get results from a search I cared about. This was adapted from some kind soul's posting somewhere on the internet but I forget where:
function getSearchResults(){
var max_rows = 1000;
var search_id = 1211;
var search = nlapiLoadSearch(null, search_id);
var results = search.runSearch();
var rows = [];
// add starting point for usage
var context = nlapiGetContext();
startingUsage = context.getRemainingUsage();
rows.push(["beginning usage", startingUsage]);
// now create the collection of result rows in 1000 row chunks
var index = 0;
do{
var chunk = results.getResults(index, index+1000);
if( ! chunk ) break;
chunk.forEach( function(row){
rows.push(row);
index++;
});
}while( chunk.length === max_rows);
// add a line that returns the remaining usage for this RESTlet
context = nlapiGetContext();
var remainingUsage = context.getRemainingUsage();
rows.push(["remaining usage",remainingUsage]);
// send back the rows
return rows;
}
This is where you get things primed by passing in your Saved Search Internal ID:
var search = nlapiLoadSearch(null, SEARCH_ID);
var resultSet = search.runSearch();
Then the code repeatedly calls getResults() to get chunks of 1000 results, this is a NetSuite limitation. Once you have this written you have to upload the script to NetSuite and configure and deploy it. The most important part is telling it what function to assign to each verb. In this case I assigned GET to execute the getSearchResults. There is a lot of work to do here, and I'm not going to type all of it out because it is worth your time to learn this part. At least enough to get the IDE to do it for you =D. You can read all about it in the "Introduction to RESTlets" guide.
Part III.
Client code can be in whatever you want that does REST the way you like to. Personally I like Python for this because the requests library is fantastic.
Here's some example Python code:
import requests
import json
url = 'https://rest.sandbox.netsuite.com/app/site/hosting/restlet.nl?script=123&deploy=1'
headers = {'Content-Type': 'application/json', 'Authorization':'NLAuth nlauth_account=1234567, nlauth_email=someone#somewhere.com, nlauth_signature=somepassword, nlauth_role=3'}
resp = requests.get(url, headers=headers)
data = resp.json()
The URL is going to be displayed to you as part of the deployment of the RESTlet. Then it's up to you to do what you want with the data that comes back.
So the things I would suggest you spend time with would be
Setting up the NetSuite IDE
Getting and reading the SuiteScript developer reference docs
Finding a good way to create REST client code in you language of choice.
I hope that helps.
I created a saved search in Netsuite and call that search using restlet. With this it is pretty lightweight and you can call the data as it is in the saved search.
Performance wise Restlet is much better than webservices.
Create a new suitelet script and deploy
Below script will give you invoice list by customer internal id
function customSearch(request, response) {
var rows = [];
var result;
var filters = [];
//9989 is customer internal id you can add more
// by pushing additional ids to array
filters.push(new nlobjSearchFilter('entity', null, 'anyOf', [9989] ));
var invoiceList = nlapiSearchRecord('invoice', null, filters, []);
// by default record limit is 1000
// taking 100 records
for (var i = 0; i < Math.min(100, invoiceList.length); i++)
{
if (parseInt(invoiceList[i].getId()) > 0) {
recordid = invoiceList[i].getId();
try {
result= nlapiLoadRecord(invoiceList[i].getRecordType(), recordid);
// pushing in to result
rows.push(result);
} catch (e) {
if (e instanceof nlobjError) {
nlapiLogExecution('DEBUG', 'system error', e.getCode() + '\n' + e.getDetails());
} else {
nlapiLogExecution('DEBUG', 'unexpected error', e.toString());
}
}
}
}
response.setContentType('JSON');
response.write(JSON.stringify({'records' : rows}));
return;
}
}
}
response.setContentType('JSON');
response.write(JSON.stringify({'records' : rows}));
return;
}
Here is what I have for getting a customer's invoices:
public function getCustomerInvoices($customer_id)
{
$service = new NetSuiteService($this->config);
$customerSearchBasic = new CustomerSearchBasic();
$searchValue = new RecordRef();
$searchValue->type = 'customer';
$searchValue->internalId = $customer_id;
$searchMultiSelectField = new SearchMultiSelectField();
setFields($searchMultiSelectField, array('operator' => 'anyOf', 'searchValue' => $searchValue));
$customerSearchBasic->internalId = $searchMultiSelectField;
$transactionSearchBasic = new TransactionSearchBasic();
$searchMultiSelectEnumField = new SearchEnumMultiSelectField();
setFields($searchMultiSelectEnumField, array('operator' => 'anyOf', 'searchValue' => "_invoice"));
$transactionSearchBasic->type = $searchMultiSelectEnumField;
$transactionSearch = new TransactionSearch();
$transactionSearch->basic = $transactionSearchBasic;
$transactionSearch->customerJoin = $customerSearchBasic;
$request = new SearchRequest();
$request->searchRecord = $transactionSearch;
$searchResponse = $service->search($request);
return $searchResponse->searchResult->recordList;
}

Request to Apache server in chat app

I'm writing a chat application for joomla (apache server) and use this construction to emulate long-polling (server side):
function get_messages($last_id) {
$time = time();
while((time() - $time) < 25) {
$sql = 'SELECT * FROM #__messages WHERE `id` >'.intval($last_id);
$db->setQuery($sql);
$rows = $db->loadAssocList();
if (count($rows)>0) {
echo 'JSON STRING HERE';
} else {
flush();
}
usleep(5000000);
}
}
How Can I optimize this part of code.
Should I use infinite looping or should I avoid while construction?
P/S: I know Apache is not best choice to write chat app for and node.js is better.
Thanks!
Infinite loops are never a good idea because they hammer your server resources. You are better off having JS providing the intermittent polling to your get_messages function. Use a timeout and embed the script on any page that shows the messages.
I'm going to answer based on the limited information I've got to help you in the broadest way possible following industry standards. You need to not code in the way you currently are because it is very inefficient and quite frankly dangerous.
Here is the mootools code required to run an intervaled polling (I've used Mootools as you said you're using Joomla, I've assumed you're using 1.6+ as 1.5 is EOL this month):
//this sets how often you want to update (in milliseconds).
setInterval('chatPoll()',2000);
//this function essentially just grabs the raw data
//from the specified url and dumps it into the specified div
function chatPoll()
{
var unixTimestamp Math.round(new Date().getTime() / 1000)
var req = new Request({
method: 'get',
url: $('ajax-alert').get('http://www.yoururltoupdate.com/file.php?last=' + (unixTimestamp-2),
data: { 'do' : '1' },
onComplete: function(response) { response.inject($('my-chat-wrapper')); }
}).send();
}
Your PHP file should look something look like this:
get_messages($_GET['last']);
function get_messages($last_id) {
$sql = 'SELECT * FROM #__messages WHERE `id` >'.intval($last_id);
$db->setQuery($sql);
$rows = $db->loadAssocList();
if (count($rows)>0) {
echo json_encode($rows);
}
}
I haven't fully tested this code but it should work and if not will definitely help answer your query as to how what you're trying to do should be achieved rather than the way you originally posted. If you really wanted to get fancy you could check out node.js as well. There is also tons of extensions for Joomla which work as chat mediums for support purposes if that's what you were after.

How to make returned from PHP Data fill MXML Flex mx:List (Using actionscript and PHP)

I am Using Flex 3 and apache with PHP 5.2.
I am searching for simple as possible way to fill my mx:List with data using POST URLRequest.
In Flex builder I am using the next code
public var variables_se:URLVariables = new URLVariables();
public var varSend_se:URLRequest = new URLRequest("DataProvider.php");
public var varLoader_se:URLLoader = new URLLoader;
public function starter():void
{
varSend_se.method = URLRequestMethod.POST;
varSend_se.data = variables_se;
varLoader_se.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader_se.addEventListener(Event.COMPLETE, completeHandler_se);
variables_se.CountOflistItemsIWant = 30;
varLoader_se.load(varSend_se);
}
public function completeHandler_se(event:Event):void
{
textFild.text += " " + String(event.target.data) + ";"; // any result will apear in some textFild
// How to make result appear as list lines, how to form PHP answer and AS3 code for it?
}
How to make result appear as list lines, how to form PHP answer and AS3 code for it (If for example I want to return random numbers from PHP in desired in CountOflistItemsIWant cuatety)?
Maybe you could make your php script echo json encoded array like so:
<?php
echo json_encode(array('first', 'second', 'foo', 'bar'));
and in flex get it, decode it and use it as argument for array data provider for your mx:List
You can find information about communicating between php and flex with use of json here: http://www.adobe.com/devnet/flex/articles/flex_php_json.html
IMHO this is a larger architectural question. Here are the options:
Create a RESTful web service and have it output data in some text format (XML or JSON). You can use the HttpService objects in Flex to make request to your PHP restful web service and set result and fault handlers accordingly. Here's the quick start: http://www.adobe.com/devnet/flex/quickstart/httpservice/
If you need to remote objects directly between Flex and PHP, AMFPHP can be used: http://www.amfphp.org/
You can create a SOAP web service in PHP, some references...
http://developer.apple.com/internet/webservices/soapphp.html
http://php.net/manual/en/book.soap.php
... and use the Flex WebService object to make calls:
http://livedocs.adobe.com/flex/3/html/data_access_3.html

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