Inserting data to MySQL table using Flex and PHP
Ok, in my last post I tried to follow Mike J. Potter's tutorial on how to read data from PHP to Flex. He actually also tried to make an example of how to write data but he left some part out.
Ofcourse I'm still just trying out the examples, making some little twists wherever I feel like adding one. To get directly to the point, I modified the PHP file in his example as follow:
<?php
$host =
"localhost";
$username =
"root";
$password =
"";
$db_name =
"flextestdb";
$mysql_connection
= mysql_connect($host, $username, $password);
mysql_select_db($db_name);
$param_username =
$_POST["username"];
$param_password =
$_POST["password"];
$text =
$param_username . $param_password;
$query =
"INSERT INTO users_tbl(username, password) VALUES('$param_username',
'$param_password')";
if (
!mysql_query($query, $mysql_connection) ){
die('ERROR: '. mysql_error() );
}
echo "INSERT
SUCCESSFUL, 1 Record Added";
?>
Pretty straight-forward. Here's the MXML code:
<?xml
version="1.0" encoding="utf-8"?>
<!--
======================================================================
Aug 1, 2008 12:27:00 PM
======================================================================
-->
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:HTTPService
id="writeData" url="http://localhost/flextest/write.php" method="POST" resultFormat="text" result="resultHandler(event)"/>
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.controls.Alert;
/*HTTPService result callback*/
public function resultHandler( event:ResultEvent ):void
{
Alert.show("Result " +
String( event.result ) );
}
/*Function to send over HTTP*/
public
function sendData():void
{
var validEntry:Boolean = !(usernameTxt.text
== "" || passwordTxt.text == "");
if (validEntry){
var
objSend:Object = new Object;
objSend.username =
usernameTxt.text;
objSend.password =
passwordTxt.text;
writeData.send(objSend);
}
else{
Alert.show("Username
and Password cannot be blank!");
}
}
]]>
</mx:Script>
<mx:Label x="10" y="10" text="Username:
"/>
<mx:TextInput x="100" y="10" id="usernameTxt"/>
<mx:Label x="10" y="50" text="Password:
"/>
<mx:TextInput x="100" y="50" id="passwordTxt"/>
<mx:Button x="10" y="100" id="sendButton" label="Send" click="sendData()"/>
</mx:Application>
I've heard about using CSS to aid in aligning your form. Yes, CSS in Flex. But I don't know how to do that yet so I'm sticking with hardcoded values. Above you will see that I tried to validate using a simple if check and the Alert class. Spket, sad to say, as of this point doesn't have support for Actionscript, that's why the Actionscript portion were all green... No code-completion feature even for the <mx:Script> tag.

The first time I tried to run the SWF file and click on the submit button I received an error saying:
[RPC Fault faultString="HTTP request error" faultCode="Server.Error.Request" faultDetail="Error: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2032: Stream Error. URL: http://localhost/write.php"]. URL: http://localhost/write.php"]
at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::faultHandler()
at mx.rpc::Responder/fault()
at mx.rpc::AsyncRequest/fault()
at DirectHTTPMessageResponder/errorHandler()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/redirectEvent()
Make sure you put the correct url in your HTTPService to avoid this, and if you ever encouter it, you know what to do.
Once you try out the app, data successfully inserted into the MySQL table. You can check the output of the app (see my previous post) to verify that the record was indeed inserted. Next time, I'm gonna try to combine these two so they don't have to be two separate swf files.


main.swf (The result list)

Resources:
http://www.adobe.com/cfusion/communityengine/index.cfm?event=showdetails&productId=2&postId=7744&loc=en_US
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Boolean.html