Tom Krcha's FlashRealtime

Hey amigo! These are my notes. I'm Platform Evangelist with Adobe.


Flash Builder 4 and PHP
Data/Services for beginners

November 6th, 2009

Flash Builder 4 logo 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

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

Flex a PHP - nove

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.

Flex a PHP - nove

If you haven’t Zend_AMF installed on your server, Flash Builder 4 will offer you to install it. Click OK.

Flex a PHP - Zend

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.

Flex a PHP

Choose PHP a click Next.

Flex a PHP - Výběr služby

Click Generate sample PHP class.

Flex a PHP krok 2

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.

Flex a PHP - vygenerování CRUD třídy dle struktury datábáze

Security Information warns you with steps you should follow, when releasing production version. Click OK.

Flex a PHP - konfigurace PHP služby

Click Next. The following screen displays a list of available services, including functions and return types. Click Finish.

Flex a PHP - dostupné funkce

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.

Flex a PHP - refresh service

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

Flex a PHP - nove

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:

Flex a PHP

Step 4 - items edit

Move to Data/Services panel, invoke context menu on type Employee and choose Generate Form

Flex a PHP

Leave Make form editable checked and go Next.

Flex a PHP - nove

Choose items, you want to keep visible/editable and click Finish.

Flex a PHP - nove

The form is generated, take it and move it right. Add Save button (btnSave) and retitle the first button to Search

Flex a PHP

Similar way we add handler On change to the List (listSearch)

Flex a PHP

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);
}

Final app preview:
Flex a PHP - zbytek

Facebook comments:

56 Comments »

  1. Nice tutorial, should be very helpful for beginners.

    LN

    Comment by Lukas Nemecek — November 7, 2009 @ 6:19 pm

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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

  7. 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

  8. Sure - just copy paste it … it’s just bunch of files.

    Comment by tom — November 10, 2009 @ 5:28 pm

  9. 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

  10. 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

  11. 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

  12. 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

  13. 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

  14. 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

  15. 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

  16. this happened to me too….. i dont know wht s wrong…. :( i’m using XAMPP ….

    Comment by jullius — December 23, 2009 @ 2:46 am

  17. 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

  18. 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

  19. 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

  20. @Ramzan: Sure you can use Flex.

    Comment by tom — January 12, 2010 @ 12:21 am

  21. 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

  22. 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

  23. 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

  24. 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

  25. 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

  26. 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

  27. 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

  28. 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

  29. How we can change charset in the sql query ?
    for example I want to display latin5_turkish_ci in datagrid but some character not display .
    Thanks.

    Comment by Ahmed — March 27, 2010 @ 9:01 pm

  30. Thanks for article :)

    Here is video tutorial: How to use Flash Builder 4 for developing RIA apps (Slovak version): http://www.flexgarden.net/2010/04/05/video-tutorial-flash-builder-4-tvorba-air-aplikacie/

    Comment by Georgik — April 5, 2010 @ 11:02 pm

  31. Great job, Georgik!

    Comment by tom — April 15, 2010 @ 1:27 pm

  32. 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 Germán — April 21, 2010 @ 4:53 pm

  33. Hi Germán,

    This means you have an error in your PHP code. Did you make any changes?

    Cheers,
    Roelof

    Comment by Roelof — April 26, 2010 @ 11:57 am

  34. Hi,
    I have the same problem like German. Only change which I done in php file is updating getAllEmployees function. I used code from this tutorial.
    I would be grateful for your help.
    Adam

    Comment by Adam — April 28, 2010 @ 1:11 am

  35. [...] more from the original source: Flash Builder 4 and PHP Data/Services for beginners … If you enjoyed this article please consider sharing [...]

    Pingback by Flash Builder 4 and PHP Data/Services for beginners … | Source code bank — April 30, 2010 @ 10:07 pm

  36. @Adam, are you sure your PHP code is 100% correct?

    Comment by Roelof — May 2, 2010 @ 11:35 am

  37. Hi there, I dont know if I am writing in a proper board but I have got a problem with activation, link i receive in email is not working…

    Comment by Anonymous — May 4, 2010 @ 3:46 am

  38. However, there have inflammed voluntary [i]amaryl side effects allergic reactions[/i] undergarments whing that the oiliness of hydroxyproline and beta-adrenergic sequencing bioassays may cat the zocoraberration of preffered sunblock failure, microaerophilic number or medicne of visine in connections with lamellar disease.

    Comment by buy online cheap phenergan — May 6, 2010 @ 7:10 am

  39. Hi! Great tutorial, i did it and i’m geting “Channel disconnected
    Channel disconnected before an acknowledgement was received” on the search button, does anyone know what the problem might be? Thank you!

    Comment by Christian — May 13, 2010 @ 6:05 pm

  40. I hope you can help with my question. I want to connect to a database that is not on the localhost, but on a web hosting server. I have entered the information correctly, but it will not connect.

    Can I connect to remote servers through the Data Services option, or do I have to code it by hand?

    Thanks

    Comment by JT — May 18, 2010 @ 3:15 am

  41. Hi.

    Love the article, and is just the thing I was looking for.

    Very new to Flash Builder too.

    When I try an implement my own version of this, I’m getting an error on
    protected function btnSearch_clickHandler(event:MouseEvent):void
    {
    getMainDataResult.token = tbldataService1.getMainData(txtSearch.text);
    }

    Saying there’s too many arguments, expecting 0. If I remove txtSearch.text it’s ok

    Any ideas why?

    Comment by David — May 20, 2010 @ 1:19 pm

  42. Sorry fixed it. Missed a ‘$q’.

    Now got other issues, but it’s the data returned.

    Comment by David — May 20, 2010 @ 1:47 pm

  43. Quite interesting tutorial. It would be great if could explain how to connect to database which is NOT located on localhost but on remote server. I’ve tried to do it on my own but without success.

    Comment by John — May 21, 2010 @ 12:00 pm

  44. Nice tutorial indeed! I wanted to extend its functionality by adding a text area control where the user can post some comment or resume for certain employee, but the following problem occurred - in the db i use a text type field but when i use getEmployee function to get the data it returns only part of the text field as if it is for example a varchar(255), …the returned string is indeed 255 symbols in length, the strange thing is that in fact in the db the text field length is as it is inserted. For example if I insert an employee and in this text field I enter longer text /more than 255 characters/ the text is inserted in the db field as it is, and also within the session when the application is used the text as it is in length is visible in the text area but when I logout and again log in only 255 of it are shown. Does anyone experience the same problem or stumble upon something similar? I just want to understand where is the problem in php when retrieving data or in flash builder?

    Comment by Slav — June 3, 2010 @ 8:16 am

  45. Hi there, great tutorial.
    I got a problem with the dataservice though. When i clic the connect to database button, it takes a while and then shows me a ‘Unable to connect to database using specified connection information java.io.EOFException’.
    Hope someone could help me see the light here.

    Thanks,
    Gaston

    Comment by Gaston — June 3, 2010 @ 7:16 pm

  46. @ 44
    I have the same problem! Any solution?

    Comment by HitBox — June 7, 2010 @ 5:11 pm

  47. I have the same problem as well.

    java.io.IOException: Server returned HTTP response code: 500

    When I use Windows Apache PHP Zend MySQL everything it runs ok, but when I put the project in the production server (iis) I’ve received:

    Send failed
    Channel.Security.Error error Error #2048 url: ‘http://www.mydomain.com.br/ph/TestePHP-debug/gateway.php’

    Comment by Philippe — June 12, 2010 @ 6:07 pm

  48. To tell you the truth, I have tried many examples online and I have always met a brick wall but this works with a small glitch. I am using the completed version of flash builder 4 so there are some changes. When you run the app, I expect that it would fetch all the employees from the database but i don’t seem to get that on start up. I suppose the creationcomplete event of the app is supposed to call getAllEmloyees method without any parameter returning all the result. So I tried to modify the code to do that.

    Then in the script block

    protected function initApp():void
    {
    getAllEmployeesResult.token = employeesService.getAllEmployees();

    }

    I expected this to fix it but somehow its not doing that. But if you do not entere= any data into the textinput and you hit search you get all the employee data back.I guess I’d have to look at it again. This is a great starting point though.

    Thanks. Nice work.

    Comment by Oluwaseun — June 23, 2010 @ 4:56 pm

  49. Hey there,
    did the Channel disconnected error ever get resolved? Does anyone know why does it happen?

    Thanks.

    Comment by Gaston — June 27, 2010 @ 2:44 am

  50. it also gives me Channel disconnected error. I’m on win (WAMP). I also tried to just configure new Data Services (without any changes in PHP), made new Button and added On Click function btnSearch_clickHandler(event) that assigns protected function btnSearch_clickHandler(event:MouseEvent):void
    {
    getAllEmployeesResult.token = employeesService.getAllEmployees();
    }

    still getting the error… does anybody know why?

    Comment by simPod — July 1, 2010 @ 1:19 pm

  51. Hello!! great tutorial I love it, a lot of thanks.

    I have only one question, I want to take only the field “lastname” from the object that I receive, how can I do it?

    Thanks.

    Comment by Palafox — July 13, 2010 @ 6:43 am

  52. You need to change the PHP script - instead of SELECT * FROM, write SELECT lastname FROM … then refresh in FB4.

    Comment by tom — July 14, 2010 @ 3:26 pm

  53. Hi! Thanks for great tutorial.

    I manage to connect with PHP and send data on my localhost (WAMP) server. When i move my application to remote web server, there is an error running app.

    Send failed Channel.Connect.Failed error NetConnection.Call.BadVersion: : url: ‘http://www.prvaliga.net/phpTest/bin-debug/gateway.php’

    Live demo on http://www.prvaliga.net/phpTest/bin-debug/phpTest.html

    Where should i change web root, paths and urls? Thanks in advice

    Comment by Nace — July 16, 2010 @ 1:19 pm

  54. re: Channel disconnected error… I too was getting this error, and couldn’t figure it out as I was letting FlashBuilder generate all of the PHP service code. I am on Windows and using WAMP.

    I discovered if I left the port blank while setting up the service I would get the ‘channel disconnected’ error. I changed the following line in the generated php service
    var $port = “”;
    to
    var $port = “3306″;

    and it works fine.

    Hope this helps.

    Comment by Charlie — July 16, 2010 @ 7:28 pm

  55. In fact for the java.io.EOFException avec flex 4, you don’t need to indicate the port and the error desappear and you can connect to your server and enjoy !!

    Bonne chance

    Comment by pierre — August 6, 2010 @ 5:07 pm

  56. Charlie, you are a genius, that was driving me mad! Thanks for the advice re port 3306.

    Comment by Andy — August 12, 2010 @ 6:28 pm

RSS feed for comments on this post. / TrackBack URL

Leave a comment