Saturday, April 9, 2011

Flex With PHP connection using URL Loader

Here is a very simple example of two way communication with database using Flex and PHP. In this example, we are sending username and password to the PHP file from Flex. PHP file then validates the input and returns the appropriate response.

This example also demonstrates the simple PHP script to establish a database (MySQL) connection and validate username and password against the table in database.

In AS3, we can use flash.net.URLLoader, URLRequest and URLVariables class to send and load data. First create a class named SendAndLoadExample.

Class SendAndLoadExample:



package {

import flash.events.*
import flash.net.*;

public class SendAndLoadExample {
public function SendAndLoadExample() {}

public function sendData(url:String, _vars:URLVariables):void {
var request:URLRequest = new URLRequest(url);
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
request.data = _vars;
request.method = URLRequestMethod.POST;
loader.addEventListener(Event.COMPLETE, handleComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
loader.load(request);
}
private function handleComplete(event:Event):void {
var loader:URLLoader = URLLoader(event.target);
trace("Par: " + loader.data.par);
trace("Message: " + loader.data.msg);
}
private function onIOError(event:IOErrorEvent):void {
trace("Error loading URL.");
}
}
}

Now, create an object of SendAndLoadExample class in Flex.

SendAndLoadExample.mxml
<mx:application layout="vertical" xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:script>
var variables:URLVariables = new URLVariables();
variables.UserName = "tushar";
variables.Password = "my_password";
mySendAndLoadExample.sendData(url, variables);
}
]]></mx:script>
<mx:button click="sendAndLoad()" label="Fetch data">
</mx:button></mx:application>





PHP Script for login check: login.php

 
$clientUserName=$_POST['UserName'];
$clientPassword=$_POST['Password'];
//////////////////////////////////////
// Host name
$host="[your server]";
// Mysql username
$username="[MySql database username]";
// Mysql password
$password="[MySql database password]";
// Database name
$db_name="[MySql database name]";
// Table name
$tbl_name="[MySql table name having usernames and passwords]";
function makeConnection() {
// Connect to server and select databse.
mysql_connect("$GLOBALS[host]", "$GLOBALS[username]",
  "$GLOBALS[password]")or die("cannot connect");
mysql_select_db("$GLOBALS[db_name]")or die("cannot select DB");
}
function fireQuery($query) {
$result=mysql_query($query);
return $result;
}
function printOutput($code, $msg){
print "par=$code&msg=$msg";
}
//////////////////////////////////////
function checkUserID($id, $password) {
$sql="SELECT * FROM $GLOBALS[tbl_name] WHERE
  userName='$id' and password='$password'";
$result=fireQuery($sql);
$count=mysql_num_rows($result);
if($count==1){
return true;
}
return false;
}
function init(){
if(isSet($GLOBALS["clientUserName"])
 && isSet($GLOBALS["clientPassword"])){
makeConnection();
if(checkUserID($GLOBALS["clientUserName"]
 , $GLOBALS["clientPassword"])){
printOutput("1", "Login successful.");
} else {
printOutput("0", "Failed to login $GLOBALS[clientUserName].");
}
} else {
printOutput("0", "Required parameters missing.");
}
}
init();
?>
However, you can also use HTTPService to send and load data in Flex. Nitin has posted a simple example of using HTTPService in flex.