pietrop.com Rotating Header Image

ActionScript 3.0, databases and server side scripting.

Italiano

Italiano

Utilizzando ActionScript, mi sono imbattuto nell’esigenza di dover eseguire query su di un database MySQL. In generale, indipendentemente dal tipo di database utilizzato, il metodo più efficiente, rapido ed indolore per far ciò, è utilizzare uno script lato server come ponte. Mi spiego meglio:

  1. ActionScript esegue lo script;
  2. lo script dialoga con il database;
  3. dallo script si fanno tutte le manipolazioni del caso;
  4. dallo script si stampa una stringa nella forma “variabile=valore” e si termina lo script;
  5. ActionScript riceve “variabile=valore” ed istanzia un oggetto “variabile” che contiene “valore”.

Ho realizzato un semplice schemino che spero possa chiarire le idee a riguardo, anche se in fondo non è niente di complicato:

ActionScript 3.0 interfacing with a server side script and a DBMS.

Dialogo tra ActionScript 3.0, uno script lato server e un DBMS.

Passiamo al codice. Supponiamo di voler ottenere l’età di una persona di cui conosciamo nome e cognome, e che le informazioni siano contenute in un database MySQL. In ActionScript, avendo appunto nome e cognome, faremo come segue:

//Variabili passate allo script, esattamente come se fosse un GET o un POST
var variables:URLVariables = new URLVariables("name=tom&surname=percivalle");
var request:URLRequest = new URLRequest();
 
//URL dello script
request.url = "http://www.example.com/script.php";
 
//Metodo utilizzato per inviare i dati allo script
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
 
//EventListener chiama la funzione completeHandler() non appena
//ha ricevuto risposta dallo script
loader.addEventListener(Event.COMPLETE, completeHandler);
 
try //Try tenta di eseguire lo script passandogli i parametri
{
    //Chiama lo script
    loader.load(request);
}
//Catch cattura le eccezioni della chiamata, ovvero gli eventuali errori
catch (error:Error)
{
    trace("Errore");
}
 
//Funzione chiamata dall'EventListener in caso di successo
function completeHandler(event:Event):void
{
    var age:URLRequest = new URLRequest(event.target.data.age);
    trace("Chiamata avvenuta con successo. Tom Percivalle ha " + age + " anni.");
}

Ora, supponiamo appunto che il nostro script sia scritto in PHP e che il suo indirizzo sia http://www.example.com/script.php

Otteniamo i parametri passati da ActionScript tramite metodo POST (avremo potuto anche usare GET), eseguiamo la query e stampiamo age=un_numero. Supponiamo che la tabella people abbia tre campi: name, surname e age. Il codice è il seguente:

<?
    mysql_connect("user", "pwd", "1.2.3.4");
    mysql_select_db("my_db");
 
    //Recupero i parametri passati da ActionScript
    $name = $_POST['name'];
    $surname = $_POST['surname'];
 
    //Eseguo la query
    $res = mysql_query("select age from people
                          where(name='$name' AND surname='$surname')");
    $res = mysql_fetch_assoc($res);
    //Stampo una stringa del tipo age=34
    print "age=".url_encode($res['age']);
    //url_encode serve nel caso in cui la stringa contenga simboli,
    //così ActionScript la parsa correttamente
 
?>

Il discorso appena fatto è valido anche per database diversi da MySQL e per linguaggi di scripting diversi da PHP; l’importante è, dallo script, “stampare” solo ed esclusivamente una stringa nel formato variabile=valore, in modo che ActionScript la possa parsare correttamente.

English

English

Using ActionScript I need querying a MySQL database. Generally speaking, the faster and easier way to execute queries in AS 3.0, is using a server side script as a bridge. More exactly:

  1. ActionScript calls the script;
  2. The script queries the database;
  3. The script executes arbitrary instructions;
  4. The script prints out a string in the form “variable=value” and terminates its execution;
  5. ActionScript reads the output “variable=value” and istances an object “variable” with the value “value”.

I’ve created a simply diagram that represents the various interactions between the parts:

ActionScript 3.0 interfacing with a server side script and a DBMS.

ActionScript 3.0 interfacing with a server side script and a DBMS.

Let’s go inside the code, and imagine that we need to retrieve the age of Tom Percivalle from a MySQL table called ‘people’. In ActionScript, we’ll call the script passing Tom Percivalle as two distinct parameters:

//Variables passed to the script, like a GET or POST method
var variables:URLVariables = new URLVariables("name=tom&surname=percivalle");
var request:URLRequest = new URLRequest();
 
//script's URL
request.url = "http://www.example.com/script.php";
 
//Select the method used to pass the parameters to the script
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
 
//EventListener calls the function completeHandler() when
//the script returns something
loader.addEventListener(Event.COMPLETE, completeHandler);
 
try //Tries to load the URL (execute the remote script)
{
    //Chiama lo script
    loader.load(request);
}
//Catches errors if an error occurs
catch (error:Error)
{
    trace("Errore");
}
 
//Function called when the script returns a parsable result
function completeHandler(event:Event):void
{
    var age:URLRequest = new URLRequest(event.target.data.age);
    trace("All right. Tom Percivalle is " + age + " years old.");
}

Now, suppose that the server side script is wrote in PHP and that its URL is http://www.example.com/script.php

To obtain the incoming parameters from ActionScript, we must use the $_POST array (or $_GET if we used the GET method to send informations to the script in ActionScript). Once we have name and surname (the two parameters), we query the database and print out the string “age=a_number”. The MySQL table, called ‘people’, has three fields: name, surname and age. The script should be as follows:

<?
    mysql_connect("user", "pwd", "1.2.3.4");
    mysql_select_db("my_db");
 
    //Retrives the POST parameters sent from ActionScript
    $name = $_POST['name'];
    $surname = $_POST['surname'];
 
    //Executes the query
    $res = mysql_query("select age from people
                          where(name='$name' AND surname='$surname')");
    $res = mysql_fetch_assoc($res);
    //Prints out the return string in the form age=a_number
    print "age=".url_encode($res['age']);
    //url_encode is used to correctly encode a string, so that
    //ActionScript can parse it correctly
 
?>

This method is intended to be a valid approach for any server side scripting language and for any database computer language. The main rule is to respect the syntax coding adopted to communicate between ActionScript 3.0 and the outside.

One Comment

  1. andrea scrive:

    Ciao, mi complimento e ti ringrazio.

    Hai risolto alla mia azienda un problema che pendeva da circa tre giorni (invio variabili con metodo POST da ActionScript a script PHP).

    Mi chiamo Andrea Sambati, sono il responsabile -sviluppo sistemi informativi- di D.S.C.. Sarei lieto, qualora tu fossi interessato, di instaurare tra te e D.S.C. una collaborazione a progetto.

    Buon lavoro.

Leave a Reply