Integrating Flex & PHP - An Introductory Tutorial
Join the DZone community and get the full member experience.
Join For FreeTen years ago or so, the World Wide Web primarily meant static HTML. Horrendous JavaScript, trivial games, and frivolous splash pages represented the common attempts at browser-based pizzazz. But in the past couple of years, a decade’s worth of server-side dominance has ironically revitalized interest in the client. Today, the best sites are using Rich Internet Applications (RIAs), tied into the server, to provide the user with an experience closer to a desktop application. RIAs are most commonly built using either JavaScript or Flash in the browser, communicating with some technology on the server. In this article I discuss how to use Flash in the browser, created using Flex (Flash content can be created using other software as well), to interact with PHP on the server.
Flex is an open-source framework (open-source as of version 3.0) managed by Adobe. The framework makes it very easy to use common elements and functionality, which can then be tied together via ActionScript, a language quite similar to JavaScript. A completed Flex project is compiled as a SWF file (pronounced “swiff”) that can run in any Web browser that has installed the Flash plugin. You can develop Flex projects using a text editor and the free Software Development Kit (SDK) or you can save yourself oodles of time by using Adobe’s commercial (but Eclipse-based) Flex Builder IDE (you can download a free trial of it here).
For the specific example, I’ll develop part of a Web-based application for managing employees. The application has two primary features:
1. The ability to add new employees.
2. A display of all the employees in a table (or a DataGrid, in Flex parlance).

I’ve chosen to focus on these particular aspects of an online application because they represent the most common client-server interactions: posting data to the server and getting data from the server. In the end, I’ll be generating these files:
• An HTML page that contains the Flash.
• The SWF file itself.
• One PHP script that receives form data and returns a text response (for adding new employees).
• One PHP script that just returns XML (for showing all current employees).
• One PHP script that just returns XML (for listing the departments).
You can download the source code and resulting files here.
Since the Flex side of things will require the three PHP scripts (and the backend database) in order to function, I’ll work through that list backwards.
Creating the Database
For this project, I’m going with a fairly routine employees/departments model, practical yet easily understood. My design has two tables: employees and departments. There’s a many-to-one relationship between them, in that each employee can only be in one department but each department can have multiple employees. For the sake of simplicity, I’m not concerning myself with department heads and company hierarchy or even all the details that might be associated with an employee or department. After you read this article, it shouldn’t be hard for you to go back in and change the particulars per your needs.
The SQL commands for creating the tables are:
CREATE TABLE `departments` (
`department_id` TINYINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`department` VARCHAR(40) NOT NULL,
UNIQUE (`department`)
)
CREATE TABLE `employees` (
`employee_id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`department_id` TINYINT UNSIGNED NOT NULL,
`first_name` VARCHAR(20) NOT NULL,
`last_name` VARCHAR(30) NOT NULL,
INDEX (`department_id`),
INDEX `name` (`last_name`, `first_name`)
)
To populate the departments table, run these INSERTs (add more departments, if you’d like):
INSERT INTO `departments` (`name`) VALUES ('Human Resources')
INSERT INTO `departments` (`name`) VALUES ('Accounting')
INSERT INTO `departments` (`name`) VALUES ('Marketing')
I’ll be using MySQL as the database application, but if you’re using another one, those same SQL92-compliant commands should work.
Viewing the Departments
In order to add new employees, the Flash application running in the browser needs access to the database-stored list of departments (see the drop-down menu in the next image). To achieve this, one PHP script will send out the department names and IDs as XML data. I call this script departments_xml.php (you can find it in the downloadable source code). The PHP code is short and reasonably documented, so I’ll just highlight a couple of aspects.
First, as this PHP script returns XML data, it must send out the proper Content-type header:
header("Content-type: text/xml");
Then the PHP script prints the root XML element, which can have any name:
echo "<departments>\n";
Finally, the script selects every department from the database and prints each out as a record:
echo "<department>
<id>{$row['department_id']}</id>
<name>{$row['department']}</name>
</department>\n";
Make note of the labels given to the elements, as they’ll be referred to in Flex. (Also, I’m using the Improved MySQL extensions, which assumes you’re using PHP 5 and MySQL 4.1 or greater; if not, change the code to the older MySQL functions.)
Viewing the Employees
The Flash application contains a DataGrid that lists every employee (see the next image). This is done using another PHP script that also sends out XML, just like departments_xml.php. This script is called employees_xml.php, and it works just like the previous script. The query here does use a join to also retrieve each employee’s department name. The outputted XML record for each employee is created by these lines:
echo "<employee>
<first_name>{$row['first_name']}</first_name>
<last_name>{$row['last_name']}</last_name>
<department>{$row['department']}</department>
</employee>\n";
Again, note the specific element names.

Adding New Employees
The third PHP script handles the adding of new employees. You could submit new records to this script using a standard HTML form, but I’m using pure Flex instead (see the next figure).
Regardless of where the data comes from, the PHP page that handles the new employee data needs to validate it, insert the record into the database, and report upon the results. The add_employee.php script in the downloadable source code does all this. Looking at that code, you’ll see that…
• I’m performing just basic validation of the three values; this could be improved upon using regular expressions.
• For extra security, I use prepared statements, which will prevent SQL injection attacks.
• The script creates no HTML, just plain text.
This last point is the most important, as the results of this script (i.e., whatever would otherwise be seen in the Web browser) will be displayed in an alert box by the Flex application (see the next two figures).


The Flex Page
If you’ve never used Flex, you should read an introductory tutorial before going further, as the following code could at best be gibberish and at worst not work for you at all. I would also again recommend using the Flex Builder IDE, which greatly facilitates development. I want to first discuss on the graphical elements of the Flex application, which include the “Add a New Employee” form and the “Current Employees” DataGrid.
For the employee’s first and last names, simple TextInputs are used (the Flex equivalent of HTML text inputs, obviously), providing each with a unique id value:
echo "<employee>
<first_name>{$row['first_name']}</first_name>
<last_name>{$row['last_name']}</last_name>
<department>{$row['department']}</department>
</employee>\n";
The department’s drop-down menu will be created in Flex using a ComboBox, which is like an HTML SELECT menu:
<mx:FormItem label="Department">
<mx:ComboBox id="department_id" labelField="name"></mx:ComboBox>
</mx:FormItem>
The ComboBox also has a unique id value. The other notable attribute here is labelField, which is assigned a value of name. The compiled SWF file running in the browser will receive the list of departments as XML data and use that data as the options for this ComboBox. For this process to work, the ComboBox needs to be told which XML element to use for the label, or visible text, for each option. In this case, that should be the department’s name. (Alternatively, you could change the XML outputted by the PHP script so that the department’s name is within an element called label; in that case, the SWF application would know to use those values automatically.)
Similarly, the DataGrid that displays all the current employees receives that information as XML and also needs to be told how to handle the associations.
<mx:DataGrid x="416" y="100" id="employees" width="45%" height="338">
<mx:columns>
<mx:DataGridColumn headerText="Department" dataField="department"/>
<mx:DataGridColumn headerText="Last Name" dataField="last_name"/>
<mx:DataGridColumn headerText="First Name" dataField="first_name"/>
</mx:columns>
</mx:DataGrid>
Within the columns subelement, each DataGridColumn is given a heading and is told which XML element’s values should be used to populate that column.
Finally, the visible page has an Add button for submitting the form. An event handler needs to be added to this element so that when it’s clicked, the data is sent to the add_employee.php script. That Flex code is
<mx:Button label="Add" id="submit" click="postAddEmployeeService.send();"/>
The last part of that says that when the button is clicked, the send() method of the postAddEmployeeService object should be called. I’ll explain that next…
Using HTTPService Objects
There are a couple of ways to communicate between Flex and an outside resource, with HTTPService being an easy and lightweight option. This is essentially a regular HTTP request, but is just being made by Flex instead of a Web browser. The application needs a unique HTTPService object for each Flex-PHP interaction, which means there are three in this example. Two are GET requests (for XML data); one is a POST request (for adding new employees). The first two are defined similarly:
<mx:HTTPService id="getDepartmentsService"
url="http://localhost:8888/flex/departments_xml.php"
result="handleDepartmentsXml(event)"
contentType="application/xml" />
<mx:HTTPService id="getEmployeesService"
url="http://localhost:8888/flex/employees_xml.php"
result="handleEmployeesXml(event)"
contentType="application/xml" />
Both HTTPServices…
• Are given a unique and descriptive id value.
• Are assigned a URL that points to the PHP script already created (change your URLs accordingly).
• Names the function to be called after the service request is completed.
• Identifies as XML data the content type expected in return.
The functions called after each service request have the same role: to assign to an element on the page—department_id, the ComboBox, and employees, the DataGrid—the data returned by the PHP script. Here’s what those functions look like (this is ActionScript code):
private function handleDepartmentsXml(e:ResultEvent):void {
department_id.dataProvider = e.result.departments.department;
}
private function handleEmployeesXml(e:ResultEvent):void {
employees.dataProvider = e.result.employees.employee;
}
Each function receives a ResultEvent object as its lone argument. The HTTP response is available through that object’s result property. Within the function, the specific element’s dataProvider property is assigned the received XML data, which is to say the ComboBox and the DataGrid are populated from that XML. But in each case, the specific subelement must be named (the individual department elements are to be used, not the root departments, and employee, not employees).
Those functions are called after the service request is completed. To actually invoke that request, the send() method must be called, which happens in an init() function:
private function init():void {
getDepartmentsService.send();
getEmployeesService.send();
}
You’ve already seen this concept: clicking the Add button invokes the postAddEmployeeService.send() method. Let’s look at how that service is defined, as it’s a bit different:
<mx:HTTPService id="postAddEmployeeService"
url="http://localhost:8888/flex/add_employee.php"
method="POST"
resultFormat="text"
result="handleEmployeeAdd(event)">
<mx:request xmlns="">
<first_name>{first_name.text}</first_name>
<last_name>{last_name.text}</last_name>
<department_id>{department_id.selectedItem.id}</department_id>
</mx:request>
</mx:HTTPService>
Again, a unique id is assigned and the appropriate URL is named. The method, which is GET by default, is here set as POST, and the resultFormat is plain text, which is what the associated PHP script returns. When the request is completed, the handleEmployeeAdd() function is to be called. As this request must also send data to the PHP script, an extra request element is added. Within it, an element is added for each piece of data. The name of the element will correspond to the $_POST array index in the PHP script (the id values in the form do not dictate the contents of $_POST). For each element value, refer to the page item’s id, then the text property for the TextInputs, and selectedItem.id for the ComboBox. For this last value, selectedItem identifies the user’s selection. This is followed by id, which is used because the values for the ComboBox will be the id elements from the XML data.
Finally, here’s what the handleEmployeeAdd() function looks like, which is called after this service request is made:
private function handleEmployeeAdd(e:ResultEvent):void {
Alert.show(String(e.result));
getEmployeesService.send();
}
This function does two things. First, it uses an alert window (similar to, but nicer than a JavaScript alert) to display the PHP script’s response. Two earlier figures show this in action. The function also resends the getEmployeesService request, in order to update the contents of the DataGrid, thereby reflecting the added employee.
Going Forward
If you put the database, the PHP scripts, and the Flex all together, you should end up with a perfectly functioning and nice Rich Internet Application. As with any technological thing you do, there’s lots of ways you can expand this example or other directions you can go. One option would be to add validators to the Flex code to pre-validate the form data (you should still keep the server-side validations, of course). And one of the great side benefits to using Flex is that you can easily turn out both a Web-based application (i.e., Flash to be run in browser) or a desktop application (thanks to Adobe AIR).
Opinions expressed by DZone contributors are their own.
Comments