This is a small sample of how to read and write data to and from PHP with Flex.
This shows some small sample code to transfer data using XML.
Here is the PHP file. Notice I have created a database and table each named test, and the table has 3 columns -> testid, name, and email. You’ll have to create that database and that table for this to work. Name this file rest.php.
<?php
//connect to mysql
$MySQLConnection = mysql_connect( "localhost", "root", "root" );
//load the database
mysql_select_db( "test" );
//get information from the test table
$Query = "SELECT * from test";
$Result = mysql_query( $Query );
/* print out your own XML */
print "<people>\n";
while( $Row = mysql_fetch_object( $Result ) )
{
print "<person><testid>".$Row->testid."</testid><name>".$Row->name."</name><email>".$Row->email."</email></person>\n";
}
print "</people>";
?>
Here is the Flex front end code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="rest_service.send()">
<mx:HTTPService id="rest_service" url="http://localhost/rest.php"/>
<mx:DataGrid left="0" right="0" top="0" bottom="0"
dataProvider="{rest_service.lastResult.people.person}">
<mx:columns>
<mx:DataGridColumn headerText="Test ID" dataField="testid"/>
<mx:DataGridColumn headerText="Name" dataField="name"/>
<mx:DataGridColumn headerText="Email" dataField="email"/>
</mx:columns>
</mx:DataGrid>
</mx:Application>
Two things to notice:
The dataProvider attribute of the DataGrid is simply traversing the XML tree. You need to be on the attribute that repeats (in this case person), and not its parent.
Notice that the DataGridColumn’s dataField attribute match the column names in the database table.
Writing data to the server.
PHP code, named write.php:
<?php $Text = "First is ".$_GET["first"]; $Text .= "\nSecond is ".$_GET["second"]; file_put_contents( "data.xml", $Text ); //you could easily write code here that will update data in a database ?>
Flex Code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:HTTPService id="writeData" url=”http://localhost/write.php” method="GET" resultFormat="text" result="resultHandler(event)"/>
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.controls.Alert;
public function resultHandler( event: ResultEvent ):void
{
Alert.show( "Result "+String(event.result) );
}
public function sendData( ):void
{
var objSend:Object = new Object;
objSend.first = textInput.text;
objSend.second = "Second Text";
writeData.send( objSend );
}
]]>
</mx:Script>
<mx:TextInput x="36" y="54" id="textInput"/>
<mx:Button x="204" y="54" label="Send" click="sendData();"/>
</mx:Application>
Notice that the method on the HTTPService is set to GET, and the PHP code is reading in values from the GET global variable. You could also change the method to POST, and then change the PHP script to read from the POST variable.