Connecting to a Database Using AMFPHP Flex 4 RemoteObject

Here’s a tutorial on how to connect to a MySQL server using AMFPHP. Everything needed to send and receive data is in the sample files including the server-side PHP code. This tutorial is loosely based on Ivan Ilijasic’s Populate components with data using AMFPHP recipe in the Adobe Flex Cookbook. Ivan’s tutorial is nice in that, like this one, it includes everything you need on both the server and client sides. This tutorial is simpler, though, in that it includes only the essentials of setting up the AMFPHP connection. (You do need to manually create the MySQL DB and the EMPLOYEE table in phpMyAdmin though. And, of course, you need to create a DB username/password.)

You can download the tutorial files (updated 6/27/10) and then follow these steps to set up the sample to access a remote DB with AMFPHP:

  1. Create a database on the server.
  2. Install AMFPHP on the server. Visit the AMFPHP website for the latest info and to download the software.
  3. Create PHP scripts to access the DB and install into the AMFPHP amf/services directory. The tutorial files include three PHP files you can copy to your services directory.
  4. Create the Flex application with a RemoteObject service.
  5. Set up the XML file to connect the RemoteObject service to the DB via AMFPHP.
  6. Add a compiler command that references the XML file.

Server Side

Creating a Database

Create a DB (using phpMyAdmin). (This tutorial uses a MySQL DB but you can use another DB. In that case, you’ll need to adjust the provided PHP script accordingly.) Here’s the EMPLOYEE table structure:

Here’s some sample data:

INSERT INTO EMPLOYEE
(EMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, JOB_ID, SALARY, COMMISSION_PCT, MANAGER_ID, DEPARTMENT_ID)
VALUES
(1, 'Jimmy', 'McNulty', 'jmcnulty@bpd.org', '999-999-9999', '2000-01-01', 1, 20000, .05, 10, 12),
(2, 'Bunk', 'Moreland', 'bmoreland@bpd.org', '999-999-9999', '2000-01-01', 1, 20000, .05, 10, 12)

Install AMFPHP on the server

Just download the AMFPHP code and copy it to a directory on your server. To see if it’s working access gateway.php; e.g., http://flexperiential.com/code/…/amf/gateway.php
if it’s installed correctly, you’ll see a confirmation:

amfphp and this gateway are installed correctly. You may now connect to this gateway from Flash.

There will be a link further down the page to the service browser but we’ll come to back to that later.

PHP Code

Copy the three EmployeeService PHP files to the services directory of the AMFPHP installation. Adjust the DB parameters for your DB:

define( "DATABASE_SERVER", "localhost");
define( "DATABASE_USERNAME", "dbusername");
define( "DATABASE_PASSWORD", "dbuserpassword");
define( "DATABASE_NAME", "employee");

At this point, you can run a couple of tests to make sure your DB is working and that the PHP code is set up correctly with AMFPHP. First, invoke EmployeeServiceTest.php (e.g., http://localhost /amf/services/emp/EmployeeServiceTest.php). You should see a display similar to the following:

array(2) {
[0]=>
object(Employee)#3 (12) {
["EmployeeID"]=>
string(1) "1"
["FirstName"]=>
string(5) "Jimmy"
["LastName"]=>
string(7) "McNulty"
["Email"]=>
string(17) "jmcnulty@bpd.org"
...

If this test is working, the next thing to check is the AMFPHP service browser. Return to the AMFPHP gateway.php page and click the service browser link. The first time you run it it will ask for the location of the gateway page. Assuming the default is correct, click Save.

If you’ve installed the EmployeeService into amfphp correctly you’ll see an emp service listed. You should be able to expand it and call the getEmployees function and get back our two friends on the Baltimore P.D. Similarly, you can call the setEmployee function and change their names.

Client Side

At this point, everything is in place on the server and you just need to import the Flex project into your workspace. The code should run, as is, except that you will need to edit the services-config.xml file to point to your server.

To keep things simple there’s no UI for these examples. A call to init() occurs automatically when the app is run and the getEmployees function traces out the information received from the server. To test writing to the remote DB, uncomment the setEmployee function call and then check your DB with phpMyAdmin to confirm that the changes have been made.
Here’s the code to create the RemoteObject service which connects to the DB:

<fx:Declarations>

	<!-- NOTE: Compiler switch "-services services-config.xml" is needed to connect EmployeeService 
	           to AMFPHP through the XML file -->
	<mx:RemoteObject id="EmployeeService" source="emp.EmployeeService" destination="EmployeeServer"
					 fault="faultHandler(event)" showBusyCursor="true">
		<mx:method name="getEmployees" result="getEmployees(event)" fault="faultHandler(event)" />
	</mx:RemoteObject>	

</fx:Declarations>

Here’s the code calls the methods on the RemoteObject service:

import mx.collections.ArrayCollection;
import mx.managers.CursorManager;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.utils.ArrayUtil;
import Project.Employee;

[Bindable]
private var _employees:ArrayCollection;

private function init():void
{
	EmployeeService.getEmployees();
	trace("called getEmployees");

	//setEmployee();
}
private function faultHandler(fault:FaultEvent):void
{
	CursorManager.removeBusyCursor();
	var errorMessage:String = "code:\n" + fault.fault.faultCode + "\n\nMessage:\n" 
		+ fault.fault.faultString + "\n\nDetail:\n" + fault.fault.faultDetail;
	trace(errorMessage);
}

private function getEmployees(e:ResultEvent):void
{
	trace('Employees are loaded.');
	_employees = new ArrayCollection(ArrayUtil.toArray(e.result) );
	for each(var employee:Employee in _employees)
	{
		trace(employee.FirstName+ " " + employee.LastName);
	}
}

private function setEmployee():void
{
	EmployeeService.setEmployee(1, "Cedric", "Daniels");
	trace("Called EmployeeService.setEmployee"); 
}

AMFPHP Configuration File (services-config.xml)

You’ll need to modify the services-config.xml file to point to your server. Just change the endpoint uri in the channel definition.

That’s it! You can now send employees back and forth from the Flex app to your server.