I'm tired of searching for Flex 3 and PHP tutorials on the web, and non of them working. Why? Because most of the tutorials you find are made for Flex 2 instead of Flex 3, and some database-relevant code has changed in this version.
So, I came up with a simple working solution, 100% Flex 3 compatible. This example will fill a Flex Data Grid with the existing data from an existent MySQL database table, allowing you to add information as well. It's still not bug-free, as it's still possible to add blank data to the table.
Here's what it looks like:The button "Adicionar" it's what actually expands the menu, allowing the user to insert new values. (I wanted to experiment with 'States' as well, so I included them). The 3 dataGrid columns are retrieving data from the 3 existing fields in the database.
1) Let's begin with the database itself: (use Apache/Wampserver to run it locally)
Database name: flex1
Table name: contactos
Username: rychas
User password: 123456
Field1: id
Field2: nome
Field3: email
And add some contacts to these fields.
You're obviously free to change these parameters, as long as you change the correspondent values in the PHP file. Create them like these if you want to use the PHP's directly.
2) The PHP coding.
This is the main file, that will read the database and output its data as XML.
Call this file "rest.php".
<?php
$MySQLConnection = mysql_connect( "localhost", "rychas", "123456" );
//connecting and picking DB
mysql_select_db( "flex1" );
//making the query from table contactos
$Query = "SELECT * from contactos";
$Result = mysql_query( $Query );
/* fetching data and output as xml */
print "<people>\n";
while( $Row = mysql_fetch_object( $Result ) )
{
print "<person><id>".$Row->id."</id><name>".$Row->nome."</name><email>".$Row->email."</email></person>\n";
}
print "</people>";
?>
If you run this file directly and check the html source code, you'll find a XML tree with the data. Flex will interpret these results.
I'm gonna leave the user adding for later. Let's get to Flex.
3) Flex 3 application
This is the entire Flex 3 code, so just create a new Project and paste this code. PLEASE be aware of the php files location; I'm using a local server (localhost) and the files are in a root folder called "flex1". If your source php is in a different location, which is more likely, change this in the third code line.
<?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/flex1/rest.php"/>
<mx:Panel width="365" id="pp" resizeEffect="Resize" height="229" layout="absolute" title="Lista de utilizadores" horizontalCenter="0" verticalCenter="5">
<mx:DataGrid dataProvider="{rest_service.lastResult.people.person}" id="lista" width="316.5" height="125" x="18.5" y="18">
<mx:columns>
<mx:DataGridColumn headerText="ID" dataField="id"/>
<mx:DataGridColumn headerText="Nome" dataField="name"/>
<mx:DataGridColumn headerText="Email" dataField="email"/>
</mx:columns>
</mx:DataGrid>
<mx:Button x="251" y="157" id="adiciona" label="Adicionar" click="update();"/>
<mx:Script>
<![CDATA[
import mx.controls.Alert;
private function update():void{
lista.enabled=true;
lista.focusEnabled;
currentState="registo";
}
]]>
</mx:Script>
</mx:Panel>
<mx:states>
<mx:State name="registo">
<mx:SetProperty target="{pp}" name="height" value="56%"/>
<mx:AddChild relativeTo="{pp}" position="lastChild">
<mx:TextInput x="18.5" y="183" id="utilizador"/>
</mx:AddChild>
<mx:AddChild relativeTo="{pp}" position="lastChild">
<mx:Text x="18.5" y="157" text="Utilizador"/>
</mx:AddChild>
<mx:AddChild relativeTo="{pp}" position="lastChild">
<mx:Text x="18.5" y="213" text="Email"/>
</mx:AddChild>
<mx:AddChild relativeTo="{pp}" position="lastChild">
<mx:TextInput x="18.5" y="237" id="email"/>
</mx:AddChild>
<mx:AddChild relativeTo="{pp}" position="lastChild">
<mx:Button x="250" y="265" label="Submeter" click="reg_user.send();"/>
</mx:AddChild>
</mx:State>
<mx:State name="outro">
<mx:SetProperty target="{pp}" name="title" value=""/>
</mx:State>
</mx:states>
<mx:HTTPService id="reg_user" result="confirma(event)" showBusyCursor="true" method="POST" url="http://localhost/flex1/add.php" useProxy="false">
<mx:request xmlns="">
<utilizador>
{utilizador.text}
</utilizador>
<email>
{email.text}
</email>
</mx:request>
</mx:HTTPService>
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
private function confirma(evt:ResultEvent):void{
mx.controls.Alert.show("Utilizador adicionado");
}
]]>
</mx:Script>
</mx:Application>
The really important thing is the first few lines, that define the dataGrid parameters. The "people.users" actually refers to the XML category that will be read. The 'dataField' specifies which label will be read by each column. If you change the XML's output in the rest.php file, you'll have to change it here as well.
4) Adding a user
This is the traditional PHP code to add something to a database. It'll just get the values sent by Flex, in the "utilizador"
Call it add.php.
<?php
$con = mysql_connect("localhost","rychas","123456");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("flex1", $con);
mysql_query("INSERT INTO contactos (nome, email)
VALUES ('$_POST[utilizador]', '$_POST[email]')");
mysql_close($con);
?>
5) You're done! Now just run the project. If you did everything right, the data should be written in the columns immediately. XML output will give you plenty of possibilities to play with, but I don't think there is a direct way of Flex connecting to a MySQL database.
7 comentários:
very nice tutorial, works 100%
Hello,
Your post is very interesting. Is it possible to make on a login system.
Thanks.
realy good. its the perfect script for noobiew like me. thnx!
Hi, I already did a lot of tutorial about this toppic "PHP, SQL and FLEX" but always get this problem [RPC Fault faultString="Default decoder could not decode result" faultCode="Client.CouldNotDecode" faultDetail="null"] can you help me?? pleeasee!
thx for the tutorial.. works great.. :D
Thank you! I am actually working in MS SQL but your example helped me to create a Flex/PHP/MS SQL application!! You made my day!!!!
wow!! excellent tutorial.
Could add functions like delete, add?
Please!!
Enviar um comentário