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:
Flash MX 2004 UI Components (UltraShock)
(Basic tutorials covering almost all UI components)
Controlling Media Components with Macromedia Flash MX 2004 Behaviors
(Media component tutorial)
Building a Tip of the Day Application (Part 2): Working with Web Services
(Web services tutorial)
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.
To complete this tutorial you will need to install the following software and files:
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:
Categories
Business Listing
Think of your screen as divided into three vertical sections:
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
-> ;
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.
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 |
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 | 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.
Add some categories to the tables using the following steps:
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');
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.
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.
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>
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>
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.
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.
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.
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.
Below is a screen shot of the completed interface of your application.
Figure 1. The completed application (screen shot)
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:
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.
Figure 2. FLA layout and movie clip grouping
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 |
| business_mc | 1 DataGrid component |
| details_mc | 5 Label components |
To set up the category section, do the following:
With the component still selected, open the Component Inspector panel and select the Schema tab. In the Schema tab:
Click OK. Your XML schema for categories should appear as in Figure 3:
Figure 3. XML Schema for the category_xml XMLConnector component
Select the Parameters tab. In the Parameters tab:
Open the Component Inspector panel and select the Bindings tab. In the Bindings tab, do the following:
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.
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.
To set up the Category section, do the following:
With the component still selected, open the Component Inspector panel and select the Schema tab. In the Schema tab:
The XML schema for this component should appear as it does in Figure 4:
Figure 5. XML schema for the business_xml XMLConnector component.
With the business_ds DataSet component selected, open the Component Inspector and select the Bindings Tab. Do the following:
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.
Figure 6. DataSet schema for business_ds
With the business_dg DataGrid component selected, select the Bindings tab in the Component Inspector panel and do the following:
Now you have bound the business_dg DataGrid component to the business_ds DataSet.
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:
| 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 | 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.
All your base work is done now. Now you need to add some ActionScript to get it working.
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:
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:
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.
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 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:
false.That’s it! You are ready to view your directory at the following URL: http://yourlocalHost/yourDirectory/yourFile.html
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:
Within each of these categories, you should see following businesses listed:
Computers
Automobiles
Restaurant
Clothing
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.)
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.