• View our reviews on Hot Scripts
  • JS Tutorial

Recent Comments

Powered by Disqus

Back to articles

Mysql access wrapper for Flash ActionScript 3 using PHP

Since flash doesn't have it's own way to connect to database, web developers usually use PHP for that purpose. Then there are many ways how to pass data to flash using XML etc. But all code snippets and tutorials I've found on the Internet are usually not multi functional and serve only for one purpose to insert data, or select data, but not both.

So I come up with a simple solution, how you can set up one PHP file, and then access and control database data from flash. You can execute any query, that could be executed in PHP.

So here's how it's done. We create PHP file, that will receive queries from flash as POST data, handle them and output serialized result. Then mysql class in flash will handle output and put it into two dimensional array and pass it to your callback function.

Here is a snippet from PHP file you need to set up. You'll need to change database connection settings to yours and enter secret code, so only you, who knows the code, could access your database:

//enter same code you'll use in flash mysql class
$code = "1234";

//checking for secret code, to know it is you who is accessing database
if(isset($_POST['secret_code']) && $_POST['secret_code'] == $code)
    //connecting to database, change connection settings to ones for your database
    $connection = mysql_connect("localhost", "user", "pass") 
                    or die (mysql_error());
    mysql_select_db("dbname") or die (mysql_error());
    //checking if query is submitted
        //executing query
        $result = mysql_query($_POST['qexec'], $connection) 
                    or die (mysql_error());
        //preparing array to return
        $res = array();
        //how many rows will be returned
        $res["row_count"] = mysql_num_rows($result);
        //if there are any rows, then put them into array
        if($res["row_count"] > 0)
            while($row = mysql_fetch_assoc($result))
                $res[] = $row;
        //serializing data
        echo http_build_query($res);

Then you create action script file in your project root directory and enter this code in it. Again you should change code, to match one in PHP file:


    public class mysql
        //define secret code to match php file
        private var secret_code:String = "1234";
        private var _this:Object = null;
        private var _success:String = "";
        private var _onerror:String = "";
        //define loader
        private var myLoader:URLLoader = new URLLoader();
        //define request
        private var request:URLRequest;
        function mysql(instant, requestURL)
            //declaring instance and request URL
            _this = instant;
            request = new URLRequest(requestURL);
            request.method = URLRequestMethod.POST;
            myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
            //defining events
            myLoader.addEventListener(Event.COMPLETE, onDataLoad);
            myLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
        public function exec(query:String, callback:String, error:String)
            //callback values
            _success = callback;
            _onerror = error;
            var variables:URLVariables = new URLVariables();
            variables.secret_code = secret_code;
            variables.qexec = query;
   = variables;
            //requesting data
        private function onDataLoad(evt:Event){
            //creating an array to return
            var arr:Array = new Array();
            //checking if there is any rows to return
            if(["row_count"] > 0)
                //going through all rows
                for(var i = 0; i <["row_count"]; i++)
                    var in_arr:Array = new Array();
                    //going through all column names
                    for (var keys:String in
                        if(keys != "row_count")
                            var base_key:String = 
                                                + 1, keys.lastIndexOf("]"));
                            in_arr[base_key] = 
                      [i + "[" + base_key + "]"];
                    //putting row array into main array
            //returning two dimensional array
        //if some input or connection error happens
        //should try again
        private function onIOError(evt:IOErrorEvent){
            _this[_onerror]("IOError: "+evt.text);
        //if some security error happens
        //should change settings on server
        private function onSecurityError(evt:SecurityErrorEvent){
            _this[_onerror]("SecurityError: "+evt.text);

And then you just use it like this:

//creating some dynamic text to post a feedback
var phptext:flash.text.TextField;
phptext = new(flash.text.TextField);
phptext.x = 10;
phptext.y = 10;
phptext.width = 1000;
phptext.text = "Loading";

/* callback function to handle results
 * in two dimensional array
function get_result(arr:Array)
    /* if array is empty, then it means
     * no rows returned
    if(arr.length == 0)
        phptext.text = "Empty result";
    else //else there are some results
        phptext.text = "Success";
        var mtexts:Array = new Array();
        for (var key:String in arr)
            var txtstr:String = "";
            mtexts[key] = new(flash.text.TextField);
            mtexts[key].x = 10;
            mtexts[key].y = 25 + (int(key) * 15);
            mtexts[key].width = 1000;
            for (var ukey:String in arr[key])
                txtstr += " " + ukey + "=" + arr[key][ukey];
            mtexts[key].text = txtstr;

/* callback function to handle errors
 * you can rerequest your query again
 * or notify user to submit their data again
function on_error(error:String)
    phptext.text = error;

/* creating instance of mysql class
 * you must pass reference to your class as first parameter (it is alwaws variable this)
 * and url where you put your PHP file, to access it
var query:mysql = new mysql(this, 

/* then you just execute query like this 
 * and also pass callback function for result as second parameter
 * and callback function for errors as third parameter
 * note that callback function must be declared before passing them as parameters
query.exec("SELECT * FROM contact WHERE ID > 3 LIMIT 10", 
            "get_result", "on_error");

Additional notes:

  • You should define new callback functions for every query if you want to handle them differently
  • You should define callback functions for delete, update and insert queries. Although they don't return any rows, empty array will be returned to result handling function to notify you of successfully executed query, and also you'll be notified if error occurs by error handling function.
  • Since whole query is passed to PHP, there is no way to implement security and input check on PHP level, you should verify data input against SQL injections etc on Flash level
  • If your server has magic quotes enabled, some queries won't be executed, because they will be stripped out. You should use stripslashes or this strip function, which works based on magic quote settings
  • IOError errors are usually connection problems and resubmitting your query will usually solve the problem, but SecurityError might be a setting problem, and queries won't work until you reconfigure your server's flash security settings

And here is whole project available for download. Just don't forget to change mysql connection settings in PHP file

You may also be interested in:

Powered by

blog comments powered by Disqus