Accessibility

Business Directory Sample: Flash MX 2004 Professional with PHP and MySQL

Sajid Saiyed

blog.ssdesigninteractive.com

Integrating Macromedia Flash with databases wasn't easy—until Flash MX 2004 Professional. Using the Flash components that ship with the Flash MX 2004, you can very easily create dynamic and engaging Rich Internet Applications (RIA).

In this tutorial, you will connect a Flash user interface with a MySQL database using PHP scripting. The application you are going to develop is a business directory. This business directory has three sections: Choose Category, Choose Business, and View Details of the Business. You will be using the Flash MX 2004 UI and Data components to populate the content in the interface.

This article will not cover all Data components. It will use XMLConnector components, Dataset components, and a few UI components. For more information on other Data components, you can see following tutorials:

Note: This tutorial will also not go into detail about installing web servers and PHP. The following Developer Center tutorials that can help with this setup, depending on your platform:

You can find more details on required software in the following Requirements section.

Requirements

To complete this tutorial you will need to install the following software and files:

Flash MX 2004 Professional

A web server (like Apache)

PHP 4.2.3 (minimum)

MySQL 3.23.39 (minimum)

Tutorials and sample files:

Level of experience required: intermediate

Planning Your First Database Project

Good and thorough planning always saves development time. Before you start, understand and plan what you intend to create. In this tutorial, your aim is to develop a business directory, which will contain the following:

Think of your screen as divided into three vertical sections:

Designing MySQL Tables

Creating the Database

The first thing that you will need is a database. Create a database called Blisting in MySQL.

If you are using web-based interface like phpMyAdmin, then you can just type the name of the database and click CREATE. If you are using command prompt, go to MySQL command prompt and type:

Mysql > CREATE DATABASE Blisting
         -> ;

Building the Tables

From the planning phase you know that there is some relation between the Category and the Business details. So you will have to create two MySQL tables: one for the categories and another one for the business details.

  1. Name the first table category. Use this SQL statement to create the table structure for the category table:

    CREATE TABLE category (
      cID tinyint(4) NOT NULL auto_increment,
      Category varchar(255) NOT NULL default '',
      PRIMARY KEY  (cID)
    ) TYPE=MyISAM;
    
    

    You just created the table called category where there are two fields, cID and Category.

    cID Category
  2. Name your second table directory. Use this SQL statement to create the directory table:

    CREATE TABLE directory (
      pID int(4) NOT NULL auto_increment,
      Category varchar(255) NOT NULL default '',
      Business varchar(255) NOT NULL default '',
      Address varchar(255) NOT NULL default '',
      Telephone varchar(255) NOT NULL default '',
      Website varchar(255) NOT NULL default '',
      Email varchar(255) NOT NULL default '',
      Details longtext NOT NULL,
      Picture varchar(255) NOT NULL default '',
      PRIMARY KEY  (pID)
    ) TYPE=MyISAM;
    
    

You just created another table called directory in which there are nine fields:

pID Category Business Address Telephone Website Email Details Picture

Note that there is a field called Category in this table. This field is required so that you can specify which category a business falls under. Also you will have to make sure the name of the category you specify here matches at least one of the categories in the category table.

Now you need to populate the tables with some dummy data.

Populating the Tables

Add some categories to the tables using the following steps:

  1. Use the following SQL statement to create categories:

    INSERT INTO category VALUES (1, 'Computers');
    INSERT INTO category VALUES (2, 'Automobiles');
    INSERT INTO category VALUES (3, 'Restaurant');
    INSERT INTO category VALUES (4, 'Clothing');
    
    
  2. Add some data to the directory table with the following SQL statement:

    INSERT INTO directory VALUES (1, 'Computers', 'Abson', 'ABSON (UK) Ltd, Campus 100, UK', '01952284303', 'http://www.abson.com', 'sales@abson.com', 'Manufacturers of quality computer products as well as scanners, digital cameras and LCD projectors. Our Site offers FAQ and technical support. \r\nContact us for your immediate needs or visit the site for more details.', 'abson.jpg');
    INSERT INTO directory VALUES (2, 'Automobiles', 'CFS Cars', '12, Sigma Towers', '9182712345', 'http://www.cfs.com', 'sales@cfs.com', 'We sell all kinds of automobile spare parts.', 'cfs.jpg');
    INSERT INTO directory VALUES (3, 'Computers', 'Tell', 'Tell technologies., Texas, USA', '8885608324', 'http://www.tell.com', 'sales@tell.com', 'Tell\'s commitment to customer value, to our team, to being direct, to operating responsibly and, ultimately, to winning continues to differentiate us from other companies. \r\nLook inside; we think customers, investors and others will find our story to be a unique one.', 'tell.jpg');
    INSERT INTO directory VALUES (6, 'Clothing', 'Illusion', '10, Park Palace II, Ahmedabad', '1234123', 'http://www.pixeltees.com/store/ssdesign', 's_saj@yahoo.com', 'We sell quality T-shirts at affordable price. We also do custom T-shirt design in single or multi colour.\r\nVisit our site for more details.', 'illusion.jpg');
    INSERT INTO directory VALUES (4, 'Restaurant', 'Indian Curry', '105 California Street, San Francisco, CA', '91827635', 'http://www.indiancurry.com', 'indiancurry@aol.com', 'Our Restaurant Specialties: Indian Food, Curry, Asian delicacies and Indian hospitality.\r\nVisit us for more details on the website.', 'indiancurry.jpg');
    INSERT INTO directory VALUES (5, 'Restaurant', 'Italiano', '2953 Baker Street, San Francisco', '65432567', 'http://italiano.com', 'sales@italiano.com', 'For a trip to Italy without the flight, Italiano provides you authentic Ilatian food.\r\n\r\nVisit us at our website. ', 'italiano.jpg');
    
    

Note that as you populate the directory table with data you are inserting JPG filenames into the Picture field. You will place your images inside a folder called images, however, the Picture value in the directory table does not contain the name of the folder, only the image filename. You will specify the folder name in the ActionScript later.

Why do this in this way? Say you decide to rename your folder containing the images. If you had mentioned the folder name in each Picture field and wanted to change the name or position of the folder, you would have to go and change all the fields. If you write the name of the image folder in ActionScript, you only have to make one change in the FLA file to change it for all images.

Creating XML Files

Now that you have populated both your database tables in the steps above, create the XML files needed to set the schema for the XMLConnector components later in the tutorial.

Note: These files contain dummy data; the actual data will come from the MySQL database.

  1. Create an XML file for the ComboBox of categories. Copy the code below and save it as category.xml.

    <menu>
    	<menu-title label="menu">
    		<menu-item label="Select Category" />
    		<menu-item label="Automobiles" />
    		<menu-item label="Computers" />
    		<menu-item label="clothing" />
    		<menu-item label="Restaurant" />
    		<menu-item label="something"/>
    	</menu-title>
    </menu>
    
    
  2. Create a second XML file to contain the details of the business. Copy the code below and save it as business.xml.

    <?xml version="1.0" encoding="UTF-8" ?> 
    <datapacket>
      <row pID="1" Business="Business1" Address="Address 1" Telephone="12345" Website="http://www.b1.com" Email="email1@something.com" Details="some text for Details." Picture="image1.jpg" /> 
      <row pID="2" Business="Business2" Address="Address 2" Telephone="67879" Website="http://www.b2.com" Email="email2@something.com" Details="some more text for Details." Picture="image2.jpg" /> 
      <row pID="3" Business="Business3" Address="Address 3" Telephone="010203" Website="http://www.b2.com" Email="email3@something.com" Details="and some more text for Details." Picture="image3.jpg" /> 
    </datapacket>
    
    

Creating PHP Files

The PHP files below are the actual files, which will work dynamically and get data from MySQL. These files fetch data from the MySQL tables and generate XML files similar to the ones you've just created.

  1. You will be using one common configuration file called config.php to connect the database. Create a file called config.php from the following code:

    <?
    $connection = mysql_connect("yourHostName", "Username", "Password") or die ('cannot reach database');
    $db = mysql_select_db("DatabaseName") or die ("this is not a valid database");
    ?>
    

    As you can see, there are four variables you have to set to connect to your database. If you named the database as mentioned above, you should write Blisting in place of DatabaseName. You will also need to use an appropriate username and password to access the database.

  2. The second PHP file generates dynamic XML for the categories. Create a new PHP file and name it category.php. Copy and paste the code below into the file.

    <?php 
    //this line includes our config file
    include_once("config.php"); 
    //this line selects the cID and Category from the table category
    $result = mysql_query("SELECT cID, Category FROM category"); 
    // And now we need to output an XML document 
    echo '<?xml version="1.0" encoding="UTF-8"?>'; 
    echo '<menu>'; 
    echo '<menu-title label="menu">';
    echo '<menu-item label="Select Category ..." />';
    //this is a loop that will fetch all entries
    while($row=mysql_fetch_array($result)){ 
        $line = '<menu-item label="'.$row[Category].'"/>'; 
        echo $line; 
    } 
    echo '</menu-title>';
    echo '</menu>'; 
    ?>
    

    This file outputs dynamic XML code that is exactly the same as the static code in the category XML file you created earlier.

  3. Create a third PHP file. This file will create dynamic XML for the business details. Name the file business.php, and copy and paste the following code into it.

    <?php 
    
    //this line includes our config file 
    include_once("config.php"); 
    //this will be used to capture the variable we will pass from flash to tell which category we are looking for
    $key = $HTTP_GET_VARS[category];
    
    $result = mysql_query("SELECT pID, Category, Business, Address, Telephone, Website, Email, Details, Picture FROM directory WHERE Category LIKE '%".$key."%'"); 
    
    // And now we need to output an XML document 
    // We use the names of columns as <row> properties. 
    
    echo '<?xml version="1.0" encoding="UTF-8"?>'; 
    echo '<datapacket>'; 
    while($row=mysql_fetch_array($result)){ 
        $line = '<row pID="'.$row[pID].'" Business="'.$row[Business].'" Address="'.$row[Address].'" Telephone="'.$row[Telephone].'" Website="'.$row[Website].'" Email="'.$row[Email].'" Details="'.$row[Details].'" Picture="'.$row[Picture].'"/>'; 
        echo $line; 
    } 
    echo '</datapacket>'; 
    ?>
    
    

    This file outputs dynamic XML code that is exactly the same as the static code in the business XML file you created earlier. Place all the PHP and XML files in a folder in your web server directory. This will be the home of your Business Directory application.

Creating Your Flash File

Below is a screen shot of the completed interface of your application.

The completed application (screen shot)

Figure 1. The completed application (screen shot)

(+) View larger

As you can see in the image above, the main application screen has three vertical sections. The first one is the Choose Category section. It contains a ComboBox component for the user to select a category.

The second section is called Select Business. Once a user selects a category, you have to display all businesses that fall in this category. So, in this section, you will use a DataGrid component to display the names of the businesses.

The third section on the right side is called Get Details. Once the user clicks a business name, you need to show all details related to that business. You will use a series of UI components to display this information:

Create the interface using Flash components:

  1. Drag and drop the above-mentioned UI components from the Components panel onto the Stage as shown in Figure 2 below.
  2. Drag two XMLConnector components and one DataSet component into the workspace.

    Note: The XMLConnector and DataSet components can be outside the Stage area as they are not visual components.

    FLA layout and movie clip grouping

    Figure 2. FLA layout and movie clip grouping

    (+) View larger

  3. Organize your application into three movie clips. Referring to Figure 2, select the component from each group on the Stage, and select Modify > Convert to Symbol to convert them to movie clip symbols. Give each new movie clip an instance name in the Property inspector as follows:

    Instance name: Contains:
    category_mc

    1 ComboBox component
    1 XMLConnector component

    business_mc

    1 DataGrid component
    1 XMLConnector component
    1 Dataset component

    details_mc

    5 Label components
    1 Loader component
    1 TextArea component

Setting Up the Category Section

To set up the category section, do the following:

  1. Double-click your category_mc movie clip to open it for editing.
  2. Select the XMLConnector component and give it an instance name of category_xml.
  3. With the component still selected, open the Component Inspector panel and select the Schema tab. In the Schema tab:

    1. Select results : XML. Click the Import Schema button in the top right corner of the tab (Import Schema button ), and select the category.xml file you created earlier.
    2. Click OK. Your XML schema for categories should appear as in Figure 3:

    XML Schema for the category_xml XMLConnector component

    Figure 3. XML Schema for the category_xml XMLConnector component

  4. Select the Parameters tab. In the Parameters tab:

    • Set the direction to receive.
    • Set the URL as category.php.
  5. Select the ComboBox component and give it an instance name of category_cb.
  6. Open the Component Inspector panel and select the Bindings tab. In the Bindings tab, do the following:

    1. Click the Plus (+) button to open the Add Binding window.
    2. Select dataprovider : Array and click OK.
    3. Set the direction to in.
    4. Double-click the Bound To value. In the Bound To dialog box that pops up, select XMLConnector : <category_xml> from the Component Path pane and menu-item : Array from the Schema Location pane.

      Bound To dialog box for the category_cb ComboBox component

      Figure 4. Bound To dialog box for the category_cb ComboBox component

Now you have bound the ComboBox to the XMLConnector, which will populate its menu items dynamically.

Setting Up the Business Section

To set up the Category section, do the following:

  1. Move out to the main Timeline. Double-click the second movie clip called business_mc.
  2. Select the XMLConnector component and give it an instance name of business_xml.
  3. With the component still selected, open the Component Inspector panel and select the Schema tab. In the Schema tab:

    1. Select results : XML. Click the Import Schema button in the top right corner of the tab (Import Schema button), and select the business.xml file you created earlier.
  4. The XML schema for this component should appear as it does in Figure 4:

    XML schema for the business_xml XMLConnector component.

    Figure 5. XML schema for the business_xml XMLConnector component.

  5. Select the Parameters tab. Set the direction to receive and leave the URL blank. (You will set the URL for this using ActionScript.)
  6. Select the DataSet component and give it an instance name of business_ds.
  7. With the business_ds DataSet component selected, open the Component Inspector and select the Bindings Tab. Do the following:

    1. Add a new binding by clicking the Plus (+) button.
    2. Select dataProvider : array.
    3. Set direction to in/out.
    4. Double-click the Bound To value entry box. In the Bound To dialog box, select business_xml (XMLConnector) in the Component Path pane and row : Array from the Schema Location pane. Click OK.
  8. The XML schema contains a lot of fields, and, without modification, the DataGrid component will display all of them. You want to show only the Business name in the DataGrid; you can do this by adding a schema to the DataSet component.

    Move to the Schema tab. Click the Plus (+) button to add a component property and, in the lower pane, enter Business as the field name and select String as the data type, as shown in Figure 6.

    DataSet schema for business_ds

    Figure 6. DataSet schema for business_ds

  9. Now select the DataGrid and give it instance name: business_dg.
  10. With the business_dg DataGrid component selected, select the Bindings tab in the Component Inspector panel and do the following:

    1. Click the Plus (+) button to add a new binding.
    2. Select dataProvider : Array in the Add Binding dialog box. Click OK.
    3. In the lower pane of the Bindings tab, set direction to in.
    4. Double-click the Bound To value entry box. In the Bound To dialog box, select DataSet, <business_ds> in the Component Path pane and dataProvider : Array in the Schema Location pane.

Now you have bound the business_dg DataGrid component to the business_ds DataSet.

Setting Up the Details Section

Go back to the main Timeline and open the third movie clip details_mc. You only have a few things to do in this section.

Give following Instance names to the components you placed in the details_mc movie clip:

Naming the components
Component Type: Title: Instance Name:
Label component Company company_txt
Label component Address address_txt
Label component Telephone tel_txt
Label component Website website_txt
Label component E-mail email_txt;
Loader component Picture picture_img
TextArea component Details details_txt

For Website and E-mail, set the HTML parameter in the Property inspector to True.

Adding Listeners

All your base work is done now. Now you need to add some ActionScript to get it working.

  1. Open the category_mc movie clip. In the first frame, add the following ActionScript.

    1 : category_xml.trigger();
    2 : comboFunction = new Object();
    3 : comboFunction.change = function (evt){
    4 :   _root.business_mc.business_xml.direction = "receive";
    5 :   _root.business_mc.business_xml.URL = "business.php?category="+evt.target.selectedItem.label;
    6 :   _root.business_mc.business_xml.trigger();
    7 :   _root.details_mc.company_txt.text = "";
    8 :   _root.details_mc.address_txt.text = "";
    9 :   _root.details_mc.tel_txt.text = "";
    10 :   _root.details_mc.email_txt.text = "";
    11 :   _root.details_mc.website_txt.text = "";
    12 :   _root.details_mc.picture_img.load("");
    13 :   _root.details_mc.details_txt.text = "";
    14 : }
    15 : category_cb.addEventListener("change", comboFunction);
    
    

    Here's what this code does:

    • Line 1: This code triggers the category_xml XMLConnector component.
    • Lines 2 to 14: This code is a listener function. This function triggers when the values in the ComboBox change when a user selects a category. Here's what various sections of the listener function do:

      • Line 4: This sets the direction of the business_xml XMLConnector in the business_mc movie clip to receive.
      • Line 5: This line sets the URL of business_xml. This URL also contains a name/value pair because you have to send a URL like business.php?category=something. The something is the category that a user selects from the ComboBox component; you extract this value with the evt.target.selectedItem.label code.

        The result generated by the business.php script will be an XML file, as mentioned earlier.

      • Line 6: This code triggers the XMLConnector business_xml inside business_mc. The trigger has to occur after you load the XML content.
      • Lines 7 to 13: These lines set the values of Business, Company, Address, Telephone, Email, Website, Picture and Details to blank. Every time a user selects a category; you have to clean up previous business details the user was viewing.
    • Line 15: This is an event listener for the category_cb ComboBox component.
  2. Double-click the business_mc movie clip and select the first frame. Add the following ActionScript on this frame.

    1 : business_dg.vScrollPolicy = "auto";
    2 : DGlistener = new Object();
    3 : //function called when you press on a cell in datagrid
    4 : DGlistener.cellPress = function(evt){
    5 :	if(evt.target==business_dg){
    6 :       var nr:Number = evt.itemIndex
    7 :	  var st:String = evt.target.selectedIndex
    8 :	  _root.details_mc.company_txt.text = business_ds.items[st].Business;
    9 :	  _root.details_mc.address_txt.text = business_ds.items[st].Address;
    10 :	  _root.details_mc.tel_txt.text = business_ds.items[st].Telephone;
    11 :	  _root.details_mc.website_txt.text = "<a href=\""+business_ds.items[st].Website+"\" target=\"_blank\">"+business_ds.items[st].Website+"</a>";
    12 :	  _root.details_mc.email_txt.text = "<a href=\"mailto:"+business_ds.items[st].Email+"\">"+business_ds.items[st].Email+"</a>";
    13 :   _root.details_mc.details_txt.text = business_ds.items[st].Details;
    14 :	  _root.details_mc.picture_img.load("images/"+business_ds.items[st].Picture);
    15 :       this.updateData(0)
    16 :	}
    17 : }
    18 : business_dg.addEventListener("cellPress", DGlistener); 
    19 : //This line turns off the column sorting
    20 : business_dg.sortableColumns = false;
    21 : stop();
    
    

    Here's what this code does:

    • Line 1: Sets the Scroll policy of the business_dg DataGrid to auto.
    • Line 3 to 20: These lines make the DataGrid listener.
    • Line 8 to 13: Inside the listener, these lines populate the UI components within the details_mc movie clip. The code sets values for the following components by assigning them values from the business_ds DataSet:

      • company_txt
      • address_txt
      • tel_txt
      • website_txt
      • email_txt
      • details_txt
    • Line 14: This sets the image path for the Loader component picture_img inside details_mc.
    • Line 20: Sets the column sorting of the Datagrid business_dg to false.
  3. Publish the movie create a SWF file.

Uploading and Testing

  1. Create a folder on your web server and call it directory. Upload all your files into this directory. This includes your HTML, SWF, and PHP files. (You don’t have to load the XML files on the server. You use the original XML files only to set the schemas for the XMLConnector components.)
  2. Create one more folder inside the directory folder and call it images. Upload all the images you specified in the database into this folder.

That’s it! You are ready to view your directory at the following URL: http://yourlocalHost/yourDirectory/yourFile.html

Appendix

  1. If you used the SQL statement from this tutorial in the section "Designing MySQL tables," then you should have one pop-up menu showing four categories:

    • Computers
    • Automobiles
    • Restaurant
    • Clothing
  2. Within each of these categories, you should see following businesses listed:

    • Computers

      • Abson
      • Tell
    • Automobiles

      • CFS Cars
    • Restaurant

      • Indian Curry
      • Italiano
    • Clothing

      • Illusion
  3. You will also require the following images for each of these businesses listed. (These images can be found in the sample files provided on the introduction page.)

    • abson.jpg
    • cfs.jpg
    • tell.jpg
    • illusion.jpg
    • indiancurry.jpg
    • italiano.jpg
  4. Take care that the images are progressive JPEG images.
  5. The size of the images should be equal to the size of the loader component picture_img in the details_mc. (If they are smaller, they will not will the entire area of the component, and, if they are bigger, you will only see a part of the image.)

Where to Go from Here

After going through this tutorial, you should have a better understanding of how Flash MX 2004 can connect with a MySQL database through PHP. Also try to study the code and architecture of the application; it will help you create a richer, more advanced RIAs.

You can also extend the same code for different purposes—like a shopping cart or an employee database.

About the author

Sajid Saiyed is a manager of interactive design at Philips Design, Bangalore, India. Sajid has more than eight years of experience in the fields of interaction design, UI design, graphic design, product design, multimedia, e-learning and RIA development. He is self-taught, which you can infer from his Bachelor of Architecture degree. (He was supposed to be designing buildings!) Sajid also did a postgraduate research fellowship in New-Media at the National Institute of Design (NID) INDIA and was a visiting faculty member there. While not loaded with work, Sajid loves to participate in design competitions. He is a design freak and loves to design just about anything.