본문 바로가기

업무/X-Internet

Flex With PHP


Flex and PHP - A simple sample

I also posted this to the Adobe Flex Builder forum...

I wrote up a small Flex Builder 2.0 sample that uses PHP to update a MySQL database, with the front end being a Flex based application. In this very simple example, we have two fields, username and email address, and a datagrid. The username and email address fields are text fields, and filling them in and clicking on the "Submit" button adds them to the database. The data grid displays all the users, with an ID and their username. Below that, a text field shows the email address of the selected user (I did this, rather than 3 columns in the datagrid, to show binding data to another field, and I think its cool) :)

Here's the code: (I don't know how to attach files to this forum!)

MySQL schema:
Note: The PHP code assumes that you have created the following table in a database called "sample":
CREATE TABLE `users` (
`userid` int(10) unsigned NOT NULL auto_increment,
`username` varchar(255) collate latin1_general_ci NOT NULL,
`emailaddress` varchar(255) collate latin1_general_ci NOT NULL,
PRIMARY KEY (`userid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=3 ;

MXML:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.macromedia.com/2005/mxml" xmlns="*" layout="absolute" creationComplete="send_data()">
<mx:Script>
<![CDATA[
private function send_data():void {
userRequest.send();
}
]]>
</mx:Script>
<mx:Form x="22" y="10" width="493">
<mx:HBox>
<mx:Label text="Username"/>
<mx:TextInput id="username"/>
</mx:HBox>
<mx:HBox>
<mx:Label text="Email Address"/>
<mx:TextInput id="emailaddress"/>
</mx:HBox>
<mx:Button label="Submit" click="send_data()"/>
</mx:Form>
<mx:DataGrid id="dgUserRequest" x="22" y="128" dataProvider="{userRequest.result.users.user}">
<mx:columns>
<mx:DataGridColumn headerText="User ID" columnName="userid"/>
<mx:DataGridColumn headerText="User Name" columnName="username"/>
</mx:columns>
</mx:DataGrid>
<mx:TextInput x="22" y="292" id="selectedemailaddress" text="{dgUserRequest.selectedItem.emailaddress}"/>
<mx:HTTPService id="userRequest" url="http://localhost/flex/php/request.php" useProxy="false" method="POST">
<mx:request xmlns="">
<username>{username.text}</username><emailaddress>{emailaddress.text}</emailaddress>
</mx:request>
</mx:HTTPService>
</mx:Application>

request.php:
NOTE: You'll likely have to change the default "username" and "password".

<?php
//connect to the database
$mysql = mysql_connect(localhost, "username", "password");

mysql_select_db( "sample" );
//if the username and email address are filled out
if( $_POST["emailaddress"] AND $_POST["username"])
{
//add the user
$Query = "INSERT INTO users VALUES ('', '".$_POST['username']."', '".$_POST['emailaddress']."')";

$Result = mysql_query( $Query );
}

//return a list of all the users
$Query = "SELECT * from users";
$Result = mysql_query( $Query );

$Return = "<users>";

while ( $User = mysql_fetch_object( $Result ) )
{
$Return .= "<user><userid>".$User->userid."</userid><username>".$User->username."</username><emailaddress>".$User->emailaddress."</emailaddress></user>";
}
$Return .= "</users>";
mysql_free_result( $Result );
print ($Return)
?>

I'll be posting other tutorials for Flex and PHP in the near future on many of the PHP focused websites. If you have comments, I'd appreciate them here before I send out samples to those sites.

Posted by Mike Potter at 03:09 PM on February 07, 2006

≪ Want an intro to LiveCycle? Live in the Bay Area?
Home
A whole page of samples for LiveCycle Designer ≫

Comments

Marc Van Norden ? 04:39 PM on February 07, 2006


I am trying to grasp flex development. I have touched php and msyql. And this tutorial among others you may have will help send me in the right direction. Where are your other postings?
Irishdancer ? 04:56 PM on February 07, 2006


where did all the MXML code go to? *wonders*
Evert ? 05:01 PM on February 07, 2006


Nice, but very insecure.. you left a major hole for SQL query injection.
jf.sal ? 06:10 PM on February 07, 2006


Thanks

Some mxml code is missing.

The best way to show flex code is to explore the new beta tool, Publish: View Source in Flash Player
Mike Potter ? 08:47 PM on February 07, 2006


Marc: My other postings are in my head. :) I'll work on some more for everyone to enjoy.

Irishdancer: Woops! Code is there, but the HTML page thinks its HTML. View source if you want, but it should be fixed now.

Evert: Yes... This example is much overly simplified. The point was to show how Flex could integrate with PHP. For resources on how to program in PHP, visitors should visit http://www.zend.com

jf.sal: Yes, good point. You can now do view source in Flash, but I didn't publish the actual application anywhere.

Mike
flashape ? 09:21 PM on February 07, 2006


dude thanks for that, i was just about to start digging into flex/php tonight.


oh yeah, about that comment by evert, he is right...even though it's a simple, whipped up example, it might be better to just not even put that out there...its like an extra one line of code to escape that input.

but anyway this post was more about flex than php, i gotcha.
jf.sal ? 09:04 PM on February 09, 2006


Hi Mike

Is possible to you make a post telling if the example works or not, for me the flash player give me the error:

TypeError: Error #1009: null has no properties.
at mx.rpc.xml::NamespaceUtil$/getLocalName()
at mx.rpc.xml::SimpleXMLDecoder/decodeXML()
at mx.rpc.xml::SimpleXMLDecoder/decodeXML()
at mx.rpc.xml::SimpleXMLDecoder/decodeXML()
at mx.rpc.xml::SimpleXMLDecoder/decodeXML()
at mx.rpc.xml::SimpleXMLDecoder/decodeXML()
at mx.rpc.http::HTTPService/http://www.macromedia.com/2005/flex/mx/internal::processResult()
at mx.rpc::AbstractInvoker/http://www.macromedia.com/2005/flex/mx/internal::resultHandler()
at flash.events::EventDispatcher/dispatchEvent()
at mx.rpc::Producer/acknowledge()
at C:\dev\enterprise_beta1\frameworks\libs\framework.swc(mx/validators/Validator)$132::DirectHTTPMessageResponder/completeHandler()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/flash.net:URLLoader::onComplete()

I have other example with PHP and MySql and give the same error, and a example with xml data give the error to.

In Alpha everything that I talk runs fine but in Beta give that error.

Your feedback is important because we dont know if is a bug or is changes to Flex Alpha.

Thanks

[MP: You need the latest version of the Flash player to get this working. It will likely only work in the Beta, not the Alpha. - Mike]
Brad ? 11:03 PM on February 10, 2006


Has anyone got this example actualy working within Flex 2.0?

Im using the exact same code and my PhP script isn't receiving any POST variables at all.
[MP: I had it working with Flex 2.0, are you using the beta or the alpha? If you send me your code at mpotter@adobe.com, I'll try to see what's wrong. - Mike]
ikon ? 11:30 AM on February 16, 2006


Mike,
Nice work... I have been having troubles lately with a similar example. Can you tell me what I need to do in order to get this to work with php/mysql installs that are not local, but on another networked machine? Basically the FES 2.0 whitepapers that I find tell me that DefaultHTTP is defined as a destination in flex-proxy-services.xml, but there is no such destination defined in the files I have downloaded. In the same vein, I can't seem to find destination examples for our type of service (php/mysql/xml). Out of the box, what do you have to do to to configure a remote php install as a destination/service? Thanks in advance for your help!! I really want to continue working on my new flex app!
Mike Potter ? 11:35 AM on February 16, 2006


By default, Flash does not allow data to be transferred from remote hosts. So, if your flash file and your webserver are on two different machines, then you need to read the following technote to allow access to your data:
http://www.macromedia.com/cfusion/knowledgebase/index.cfm?id=tn_14213

Mike
ferry ? 11:38 AM on February 21, 2006


i want to know how to connect database with flex 1.5 and database using microsoft access (mdb).
if can't using mdb,it's ok with mySQL.
please send me simple application to show me.
thankyou verymuch.
GBU.
[Sorry, I don't have any experience with Flex 1.5... If you're using Flex 2.0, then the example that I've provided above should help you out. - Mike]
milan ? 05:44 AM on February 22, 2006


Thanks for this nice example. I'm wondering why nobody else is working on mysql-php-flex2 solutions? Since flex2 allow compiled swf on the client, I can see quite a lot of possibilities, using of php frameworks like cake and many others. Majority of developers are talking just about *enterprise* RIA systems with java middle tier (j2ee,ejb). But I think there is also a place for smaller, less enterprise, but maybe faster and more scalable systems...Do you know for any place with such devepment?
[I totally agree that there's a place for smaller and faster systems, using PHP and Flex. A few people have written me back after my last article telling me that they're working on something, but I haven't seen anything completed yet... Patience though, Flex 2 has only been in beta for a few weeks! :) - Mike]
johnny ? 07:02 PM on March 03, 2006


Hey its been three weeks where's the code, dude?
[Not sure what you mean, the code is in the posting... There's also another sample using AMFPHP in my blog, http://blogs.adobe.com/mikepotter/ - Mike]
Greg Starr ? 07:34 AM on March 08, 2006


!!Found the MXML!!
Hey everyone. There is no missing MXML code here.... We all forgot that we are trying to view tags embedded in a very forgiving html tag based envirnoment. Just View the source and Viola! Should make it much easier now
Marcelo ? 08:04 PM on March 16, 2006


Hi I have this error:
code:Channel.Security.Error string:'Security error accessing url' detail:'Destination: DefaultHTTP'
at mx.rpc::AbstractInvoker/http://www.macromedia.com/2005/flex/mx/internal::faultHandler()
at flash.events::EventDispatcher/dispatchEvent()
at mx.messaging::MessageAgent/fault()
at mx.messaging::Producer/fault()
at C:\dev\enterprise_beta1\frameworks\libs\framework.swc(mx/validators/Validator)$132::DirectHTTPMessageResponder/securityErrorHandler()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/flash.net:URLLoader::redirectEvent()

Error: code:Channel.Security.Error string:'Security error accessing url' detail:'Destination: DefaultHTTP'
at mx.rpc::AbstractInvoker/http://www.macromedia.com/2005/flex/mx/internal::faultHandler()
at flash.events::EventDispatcher/dispatchEvent()
at mx.messaging::MessageAgent/fault()
at mx.messaging::Producer/fault()
at C:\dev\enterprise_beta1\frameworks\libs\framework.swc(mx/validators/Validator)$132::DirectHTTPMessageResponder/securityErrorHandler()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/flash.net:URLLoader::redirectEvent()

thanks

[Make sure the Flash application is accessing the same server as its on. In my case, its localhost. - Mike]
Ivan ? 02:49 PM on March 17, 2006


Mike thank you for the example.


It is amazing what flex can do. I don't know why took me until v2 beta to found out about it!!!


[That's some snazzy website you have at http://bakedweb.com - M]
jeb1138 ? 02:03 PM on April 04, 2006


Looks like columnName has changed to dataField in the latest beta, yeah?

Also, your code above should have:
$Return = "";
instead of:
$Return = "";
right?

Thanks for the great intro to php/flex/mysql!

[Yes, I think you're right... I don't see the difference in the Return statement though? - Mike]
Israel Gaytan ? 10:42 PM on April 05, 2006


Hello this is a useful sample, and got a question , can flex integrate with amfphp? i mean flash remoting for php?


Greetings

Israel
[Yes, please see my tutorial posted here: http://devzone.zend.com/node/view/id/11]
Zorro ? 01:22 PM on April 06, 2006


Hi Mike,
is very nice that you writing about very interesting thinks!
Please make a QUALITY SAVED source posting...You can see every beginner with Flex have problem to run/install/Test your great source!

Kind regards
Zorro
Phiphou ? 01:00 PM on April 18, 2006


Hi everybody

I've just tried the 2.0 flex beta...These are my first tests on flex. I tried your example but I encounter an error on this two lines :


Flex says :


Cannot resolve attribute 'columnName' for component type mx.controls.dataGridClasses.DataGridColumn.

I've been looking flex help content for a while but it has been unsuccesfull.

Can you help me ?

Remember that I'm a really newbie in Flex, so your answer has to be as simple as possible

Thanks...

[M - I believe that's been changed to "dataField" in the latest beta.]
Phiphou ? 01:13 PM on April 19, 2006


Thanks Mike, your advice was good...

I succeed making your sample works , but I realize how complex it will be for me without any french or very basics ressources.


For instance, when I tried to publish this sample, I just copied the entire directory (C:\Documents and Settings\phillipe\My Documents\Flex\test) into my website root. Is it the right way ? I believe not, but didn't found any help...

Do you know any french or very basic english ressource (I meam basic ressource, not basic english)

Thanks...
steveosteen ? 01:57 PM on April 20, 2006


Hi,
I use Flex plugin with Eclipse.
(Eclipse is the most important and open source tool I never imagined)
With Eclipse you can write Java, Actionscript with FDT plugin, Php with the php toolset plugin but you must install php server and a mysql server like XAMPP...You can make C++ in eclipse, this is an other great thing.

But, I understand the power of flex with design view and code view. I tried your tutorial, everything seems easy, but there is just a little problem :
""Could not resolve to a component implementation. ""
(Problems line 2)
What is the answer to this problem ???
So, I follow your tutorial, everything is installed,
File -> New project -> Flex Project -> Specify the Flex server technology you want to use :
1. None
2. Cold Fusion Flash Remoting Service
3. Flex Data Services...
I choose None (???) because I work with php and coldfusion is not installed etc...

-> Create a Flex Project -> Project Name : TestPhpFlex...
And there is an error in the line 2 and in the Design panel I can't add component etc etc... any idea or advice
Thanks for any answer.
And Flex is a very great Tool.
murali ? 09:10 AM on April 22, 2006


thank you
Phiphou ? 11:16 AM on April 22, 2006


Hi,


For those who can't run properly this code, here is my sample, witch is based on Mike's one, with just a few changes...I'm working with Flex beta 2, no server (I use Apache to handle my php scripts).

I think the "Could not resolve to a component implementation." message means you cannot place this into this type of component. I had the same problem with the tag, that I replaced with a in another application.

Don't forget to change the 'columnName' to 'dataField' as Mike said.

The code :

private function send_data():void {
userRequest.send();
}
]]>

http://yourserver/photos/{dgUserRequest.selectedItem.userimage}

{username.text}{emailaddress.text}

Hope it will help you (I'm a really newbie in Flex...)
azreal ? 11:40 PM on June 12, 2006


I'm trying to build something similar to what you've created above.
I need to create DataGrid columns in dynamic way though. Maybe you had similar problem before. I'm new to flex and actionscript.

thanks.
Cliffstah ? 06:44 AM on July 12, 2006


Security holes, missing code, broken tab order..

Hello Adobe ;-P