Check out "Do you speak JavaScript?" - my latest video course on advanced JavaScript.
Language APIs, Popular Concepts, Design Patterns, Advanced Techniques In the Browser

Load MySQL data in Flash with AS3

There are some things that I'm doing in almost every project. Loading of data in Flash is actually one of them. In this article I'll show you how to load information from MySQL database. We will use PHP as a junction between the Flash and the database. You need an Apache server like XAMPP or EasyPHP installed or just a hosting account that supports php.

Download the source files from here. Unrar the archive and upload "get.php" file on your server. Open "flash.fla" and "App.as" with Flash. Let's take a look at the action script code:

package {
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.net.URLRequestMethod;
    import flash.text.TextField;
    import flash.events.IOErrorEvent public class App extends MovieClip {
      public static
      const URL: String = "http://.../get.php";
      private
      var _loader: URLLoader;
      private
      var _request: URLRequest;
      public
      function App(): void {
        output("constructor");
        loadData();
      }
      private
      function loadData(): void {
        output("loadData");
        var randomParam: String = "?p=" + Math.floor(Math.random() * (10000000));
        _loader = new URLLoader();
        _request = new URLRequest(URL + randomParam);
        _request.method = URLRequestMethod.POST;
        _loader.addEventListener(Event.COMPLETE, onLoadData);
        _loader.addEventListener(IOErrorEvent.IO_ERROR, onDataFiledToLoad);
        _loader.addEventListener(IOErrorEvent.NETWORK_ERROR, onDataFiledToLoad);
        _loader.addEventListener(IOErrorEvent.VERIFY_ERROR, onDataFiledToLoad);
        _loader.addEventListener(IOErrorEvent.DISK_ERROR, onDataFiledToLoad);
        _loader.load(_request);
      }
      public
      function onLoadData(e: Event): void {
        output("onLoadData result=" + e.target.data);
      }
      private
      function onDataFiledToLoad(e: IOErrorEvent): void {
        output("onDataFiledToLoad error=" + e.text);
      }
      public
      function output(str: String): void {
        var text: String = field.text;
        field.text = "> " + str + "n" + text;
      }
    }
  }

Change the value of the "URL" constant on line 13. For example if your site is "www.site.com" and you upload the "get.php" file on "www.site.com/get.php" you have to set

public static const URL:String = "http://www.site.com/get.php";

In line 24 I'm defining a random parameter that we will add to the URL to prevent the caching of the data. The handlers of the Loader object are set from line 28 to 32. If you check the fla file will see that there is an empty text field on the stage. I'm using it to show the processes of our small application. The method "output" adds text to the field. The result of the php file is accessible in "onLoadData" method, i.e. "e.target.data". In this example the php file returns only a text, but usually in real projects I'm using xml. So, when the data is loaded we send the text to our text field (line 36).Before compiling the flash application we need a MySQL database and a table to test with. Here are several SQL commands that will create the necessary things on the server:

CREATE DATABASE `test`
    DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
    USE `test`;
    CREATE TABLE `data` (`id`
      int(11) NOT NULL auto_increment, `name`
      varchar(250) NOT NULL, `city`
      varchar(250) NOT NULL, PRIMARY KEY(`id`)) ENGINE = MyISAM DEFAULT CHARSET = latin1 AUTO_INCREMENT = 5;
    INSERT INTO `data` (`id`, `name`, `city`) VALUES(1, 'John Smith', 'London'), (2, 'Martin Blackwood', 'Paris'), (3, 'David Boomhead', 'Praha'), (4, 'Mark Banford', 'Chicago');

If you don't know how to run these commands check out here.The "get.php" file:

// defining main variables
    $dbHost = "localhost";
    $dbUser = "root";
    $dbPass = "";
    $dbName = "test";
    $dbTable = "data";
    // connecting and selecting database
    @mysql_connect($dbHost, $dbUser, $dbPass) or die(mysql_error());
    @mysql_select_db($dbName) or die(mysql_error());
    // getting data
    $data = "";
    $res = mysql_query("SELECT * FROM ".$dbTable.
      " ORDER BY id") or die(mysql_error());
    while ($row = mysql_fetch_object($res)) {
      $data. = "nname=".$row - > name.
      ", ";
      $data. = "city=".$row - > city;
    }
    die($data);

You have to change the variables in lines 4, 5 and 6 depending on your server's settings. After this little change we are ready to launch our app. Return to Flash, hold Ctrl key and press Enter. The content of the text field should be change to:

> onLoadData result=name=John Smith, city=Londonname=Martin Blackwood, city=Parisname=David Boomhead, city=Prahaname=Mark Banford, city=Chicago> loadData> constructor
If you enjoy this post, share it on Twitter, Facebook or LinkedIn.