Flash Builder 4 and PHP
Data/Services for beginners
November 6th, 2009
Application that you create in Flex 4 uses PHP and MySQL database. It shows the most simple and the most recent approach for working with data in Flash Builder 4/Flex 4. Basically it’s just a few clicks, which generate the necessary code. We use Flash Builder 4 Beta 2 introduced at MAX 2009.
This tutorial provides a base for working with data in Flex 4 - to understand the deeper options I recommend PHP and Flex tutorial by my fellow evangelist MIHAI CORLAN Flex for PHP developers [en].
Note: This article is English translation of my Czech article published at Zdrojak.root.cz - Jak na to: Spojení Flex 4 a PHP ve Flash Builderu 4 [cz]. It can contain some Czech titles or texts in demos, just disregard and use what fits you the best.
Required software
- HTTP, PHP 5, MySQL 5 server (e.g. for Mac MAMP, for Win WAMP)
- Flash Builder 4 Beta 2
- Flash Player 10 (installed with Flash Builder 4)
- Optional Zend Framework (if you do not have him Flash Builder will install itself 4)
Finished app (source code can be displayed using the View Source context menu in the application)
Source-code
- Flex a PHP (just for check)
- Employee database in SQL (you need this, we will search in it)
Data/Services panel
Flash Builder 4 introduced Data/Services panel, which simplifies working with data services like Web Services, PHP, ColdFusion, Java (Blaze DS, LiveCycle DS) or simple HTTPService.
Data/Services panel significantly speeds up the overall development of RIA applications. Manages connections with data and separates the code to work with services from your code. This approach allows you to create a RIA as E-shop a few days and with the administration.
Along with Data/Services there is a new Network Monitor panel for debugging and monitoring request/response data transfer between client and server.
Step 1 - Create a project in Flash Builder 4
File -> New -> Flex Project

Enter the name of the project “ZdrojakFlexPHP, select Application server type “PHP” and click Next.
Make sure the HTTP server is running, set the Web root which is the root folder for the Web server. Also, set the Root URL - the address targeting Web root - and click Validate Configuration.
Leave the default settings in Compiled Flex application location and click Finish.

If you haven’t Zend_AMF installed on your server, Flash Builder 4 will offer you to install it. Click OK.
Following code is generated. Declarations block contains services.
<?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/halo" minWidth="1024" minHeight="768"> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> </s:Application>
Step 2 - Add data service
V panelu Data/Services klikneme na Connect to Data/Service.
Choose PHP a click Next.
Click Generate sample PHP class.
Flash Builder 4 can generate PHP backend classes without writing a single line of code. Simply connect to the database and select the target table. It automatically generates class with all the basic functions according to the CRUD methodology (Create Read Update Delete). This step greatly simplifies the overall connection.
Fill in your access data. Click Connect to Database - available tables load up. Select table employees. Primary key emp_no should be chosen automatically. Click OK.
Security Information warns you with steps you should follow, when releasing production version. Click OK.
Click Next. The following screen displays a list of available services, including functions and return types. Click Finish.
EmployeesService has been added to Data/Services panel. Together with this you can find EmployeesService.php on the server (in services folder) containing the following features:
- __construct - establish connection
- getAllIEmployees - returns all employees
- getEmployeesByID - returns an employee
- createEmployees - creates an employee
- updateEmployees - updates an employee
- deleteEmployees - deletes an employee
- count - returns count of all employees
- getEmployees_paged - returns employees with paging support - check ListPaged component
The code is set and ready to use. Just make few adjustments to getAllEmployees function (in EmployeesService.php) to enable database search (parameter $q).
public function getAllEmployees($q) { $sql = "SELECT * FROM $this->tablename WHERE first_name LIKE '%$q%' OR last_name LIKE '%$q%' OR email_address LIKE '%$q%'"; $stmt = mysqli_prepare($this->connection,$sql); $this->throwExceptionOnError(); mysqli_stmt_execute($stmt); $this->throwExceptionOnError(); $rows = array(); mysqli_stmt_bind_result($stmt, $row->emp_no, $row->birth_date, $row->first_name, $row->last_name, $row->gender, $row->hire_date, $row->phone_no, $row->email_address, $row->job_title); while (mysqli_stmt_fetch($stmt)) { $rows[] = $row; $row = new stdClass(); mysqli_stmt_bind_result($stmt, $row->emp_no, $row->birth_date, $row->first_name, $row->last_name, $row->gender, $row->hire_date, $row->phone_no, $row->email_address, $row->job_title); } mysqli_stmt_free_result($stmt); mysqli_close($this->connection); return $rows; }
PHP is ready now.
Let’s move to Flash Builder and refresh the service using Refresh button. The changes will apply. Function getAllEmployees should now accept search string parameter q:Object.
After restoring we have to set the correct return type. We
After refreshing we have to set the correct return type. Invoke the context menu on getAllEmployees, select Configure Return Type -> Use an existing data type from the drop-down box select the field staff - Employees[].
Step 3 - Create Flex UI for search
Lay out components List, TextInput and Button as on following figure and assign them the following ids: listSearch, txtSearch, btnSearch
Drag getAlllEmployees from Data/Services panel and drop it on Button (btnSearch) - directly in Design view. This action generates an event handler with a service call. Instead of q pass txtSearch.text.
protected function btnSearch_clickHandler(event:MouseEvent):void { getAllEmployeesResult.token = employeesService.getAllEmployees(txtSearch.text); }
We have to bind search result to the list listSearch using dataProvider. Braces represent binding - if [Bindable] variable changes, the changes are automatically reflected. At the same time set the labelField to last_name. You can play with better label representation by adjusting labelFunction and itemRenderer - recommended to explore. Also note that we are working with lastResult - or the last result of the call.
<s:List x="10" y="40" width="280" height="329" id="listSearch" dataProvider="{getAllEmployeesResult.lastResult}" labelField="last_name"></s:List>Test the app, if it does, what it is supposed to. It should look like this:

Step 4 - items edit
Move to Data/Services panel, invoke context menu on type Employee and choose Generate Form…
Leave Make form editable checked and go Next.
Choose items, you want to keep visible/editable and click Finish.
The form is generated, take it and move it right. Add Save button (btnSave) and retitle the first button to Search
Similar way we add handler On change to the List (listSearch)

employee variable is set choosing an item from the list. Final code:
protected function listSearch_selectionChangedHandler(event:IndexChangedEvent):void { employees = listSearch.selectedItem; }
Step 5 - Save update
Drag-and-drop updateEmployee from Data/Services to btnSave. Change item to employee and thanks to two-way binding we have fully-editable of the item. Handler should look like this:
protected function btnSave_clickHandler(event:MouseEvent):void { updateEmployeesResult.token = employeesService.updateEmployees(employees); }
28 Comments »
RSS feed for comments on this post. / TrackBack URL

















Nice tutorial, should be very helpful for beginners.
–
LN
Comment by Lukas Nemecek — November 7, 2009 @ 6:19 pm
Any way to use it with standard AIR (FLASH BASED) project? i’m get enought to see all this cool feature implemented only for flex side of developers, out there there are still As3 developer that don’t use flex framework..
Comment by Snick — November 8, 2009 @ 7:36 pm
It is a really nice tutorial. Too bad, for me, the configure php service dialog’s sample generation fails after I select the table name…it finds the table but crashes before the pk can be displayed.
Comment by flipper — November 9, 2009 @ 2:55 am
Flash Builder will allow you to create AS3 only projects, however the Data Services will only work on Flex projects.
However with some sneaky modifications you can include the right libraries into a AS3 project to wrap the core web services (com.adobe.fiber).
Try not to think of flash as different then flex .. You can still do everything you can in flash, in flex. Flex is simply an additional set of libraries.
But check out the LiveCycle packages (com.adobe.fiber)
go to: http://livedocs.adobe.com/flex/gumbo/langref/ and in the top left, under filters select LiveCycle 3, then hit “show table of contents” on the top right. This will expose all of the com.adobe.fiber packages, which are currently the packages used when using the automatic code generation in flex builder.
Comment by Method — November 9, 2009 @ 7:52 am
We will figure it out. Let’s follow on here http://forums.adobe.com/thread/519648?tstart=0
Comment by tom — November 10, 2009 @ 10:54 am
Snick - it uses Flex classes for connecting to database. Flex is also set of RPC classes, thus it can’t be used outside of Flex.
Comment by tom — November 10, 2009 @ 10:55 am
Will this work on a shared server? I wonder if Zend Framework can be installed in shared web space.
Comment by Phil — November 10, 2009 @ 4:21 pm
Sure - just copy paste it … it’s just bunch of files.
Comment by tom — November 10, 2009 @ 5:28 pm
As noted on the adobe forums discussion, the issue I ran into must have come from using a version of php that was too stale.
This is a great tutorial. Thank you for posting it!
I also wonder about the zend amf component on a shared hosted server. Are we sure that because zend amf comes with flash builder 4, that it’s ok to deploy? Hope so.
Comment by flipper — November 11, 2009 @ 2:57 am
You can always download Zend framework from http://framework.zend.com/ and use it. You don’t have to use Zend, which is installed by Flash Builder.
Comment by tom — November 12, 2009 @ 10:43 am
I didn’t realize that the zend framework was under an MIT license.
Is there any reason that the techniques shown in the tutorial, and the flash builder data services, would be considered inadequate for production use? What I mean is, sometimes code generated by wizards is quick but not really robust. I remember when Ted Patrick made a blog post about the flex 3 crud wizard, some people commented that it was good for showing off flex 3 a bit but not worthy of consideration for a production app. (http://www.onflex.org/ted/2007/09/flex-3beta-2-crud-wizard-for-aspnet-php.php)
The features shown in this tutorial look pretty worthy to my eye but I’m very new to flex. I hope this stuff is robust enough for use in at least some production situations?
Comment by flipper — November 17, 2009 @ 4:34 am
The good thing is that Flex code is in this case [Managed] by Flash Builder 4. So you will never be touching it, which isolates it from bugs caused by developer.
There is nothing better than go ahead and try it.
Comment by tom — November 17, 2009 @ 3:07 pm
Do happen to know if the Data Services tab in the flash builder IDE works with other data services? What if one is using weborb or BlazeDS?
Comment by flipper — November 17, 2009 @ 6:44 pm
Hi,
This is very good example for those who are beginner in action script.
This example help me a lot to connect php server.
Comment by prashant kumar — December 17, 2009 @ 9:17 am
when i’am in step “generate sample PHP service” (conect flahsh b. on mysql)
.. i cliked in a button “connect to Database” , and this ‘fatal error’ is ’show’ :
Fatal error: Maximum execution time of 60 seconds exceeded in C:\xampp\php\PEAR\Zend\Db\Adapter\Pdo\Abstract.php on line 0
this happened wiht somemore else?
what’s can be wrong???
Comment by rafa — December 22, 2009 @ 8:10 pm
this happened to me too….. i dont know wht s wrong….
i’m using XAMPP ….
Comment by jullius — December 23, 2009 @ 2:46 am
hi
i am very new to flex so i followed this tut. i get this error in a dialog:
Channel disconnected
Channel disconnected before an acknowledgement was received
what am i doing wrong?
Comment by ron — December 24, 2009 @ 2:44 pm
I went back to this example app which I built and had running in Nov and I too now get that error:
Channel disconnected
Channel disconnected before an acknowledgement was
Comment by flipper — January 2, 2010 @ 9:22 pm
Hi,
Thanks for the tutorial but i have a few question.
I am now developing online game and searching a way to save data to mysql from the game.
Can i use flex for this purpose? Or i need to save it from as3 file etc?
Thanks,
Ramzan
Comment by Ramzan — January 4, 2010 @ 10:38 am
@Ramzan: Sure you can use Flex.
Comment by tom — January 12, 2010 @ 12:21 am
Guys, there has been some problems with XAMPP read more here: http://forums.adobe.com/thread/519648?tstart=0
Comment by tom — January 12, 2010 @ 12:21 am
Thanks for posting this up does make this seems really cool to play with.
I do have an issue and maybe somewhere knows how to get around it.
By staying inside the Flash Builder and using the fancy generate / drag and drop I run into the following issue:
My development environment is not on the root URL of the web server. Each Developer in my company has their own area and we work with svn so on the development server everyone has a URL like this to work with:
http://internalserver/~username/projects/projectNam/trunk
Almost everything seems like I could get it to work IF I could just get flash builder to be not so dependent on having server root url and paths.
I tell Flash Builder the root of the project and url but in the end its so stubborn and tries to include things from the / and not /~user/projects/….
Can Flash Builder work like this outside of server roots and paths? I would hate to have to create a separate domain name for each project just for dev work?
Comment by Rob — January 13, 2010 @ 11:49 am
Tom I’m one of the people there reporting that an update of xampp worked for me. But as noted above, after a couple weeks of not touching flex 4 or php or mysql the sample project that I built with your tutorial fails with the channel disconnect error.
Comment by flipper — January 16, 2010 @ 7:15 am
I get this error while connecting in
Generate Sample PHP Service -> Generate from database
Unable to connect to database using specified connection information.
java.io.IOException: Server returned HTTP response code: 500 for URL: http://localhost/php5/tempgateway.php
Comment by Robin Thomas — January 16, 2010 @ 11:55 am
I set up a new virtual server to see if I could get this to work again.
A new error - after the data service has been created, or configured, the returned data type is not Employees[] as the screenshot shows. Every place that the screenshot shows Employees[] I have Object. I don’t know how to adjust that or why this time it didn’t automatically show up as expected.
This makes the rest of the tutorial impossible to follow. Hope someone will provide input.
Comment by flipper — January 18, 2010 @ 3:27 am
I see - can you send me exact setup you have on your machine? Which server, PHP version, DB version, FB4 version…
Comment by tom — January 18, 2010 @ 8:11 pm
Sure it’s windows 7 pro; xampp 1.7.2; php 5.3.0; apache 2.2.12; mysql 5.1.37. FB is 4 beta 2. I let FB install zend and didn’t update that.
Comment by flipper — January 22, 2010 @ 10:39 am
if you get the error with localhost/tempgateway.php java.io.FileNoteFoundException then you have configured the wrong path to the server.
in my case it looked like this:
Web root:
C:/xampp/htdocs/snow
Root URL:
http://localhost/snow/
type in your settings and it will work!
thanks,
ben
Comment by ben — February 25, 2010 @ 7:59 pm