26
Retrieve data from mySQL with Flash CS3 We have seen how to enter data in a database with Flash CS3. In that case, we had a form in Flash that sent the data of user to a PHP script that turn them inserted in the database mySQL. Now we see how to retrieve this data. As I said earlier, Flash and mySQL can not communicate directly and therefore also in this if we make use of a server-side script (PHP). In addition we need that the PHP output must be XML format. So the first thing we need to create a file that is running the PHP Query the database and returns XML output to Flash. Only at this point we can see data with Flash in ways and forms with which we like. In this case, I use a DataGrid component. This tutorial leans on the same database and table "clients" used in the tutorial insert data in a database with Flash CS3 . I create a PHP file that retrieves data from table "clients" and shoots out an output in XML format: PHP Code: <?php /* ************************************* Retrieve data from DataBase with Flash CS3 http://www.flepstudio.org Author: Filippo Lughi version 1.0 ************************************* */ /******** CHANGE YOUR DATABASE SETTING *******/ $dbhost = 'localhost'; // database host ( usually localhost ) $dbuser = 'root'; // database username $dbpass = 'root'; // database password $dbname = 'dbname'; // database name $mysql = mysql_connect($dbhost,$dbuser,$dbpass); mysql_select_db($dbname); $Query="SELECT * from clients";

Retrieve Data From MySQL With Flash CS3

Embed Size (px)

Citation preview

Retrieve data from mySQL with Flash CS3

We have seen how to enter data in a database with Flash CS3. In that case, we had a form in Flash that sent the data of user to a PHP script that turn them inserted in the database mySQL.

Now we see how to retrieve this data. As I said earlier, Flash and mySQL can not communicate directly and therefore also in this if we make use of a server-side script (PHP). In addition we need that the PHP output must be XML format.So the first thing we need to create a file that is running the PHP Query the database and returns XML output to Flash.

Only at this point we can see data with Flash in ways and forms with which we like. In this case, I use a DataGrid component.

This tutorial leans on the same database and table "clients" used in the tutorial insert data in a database with Flash CS3. I create a PHP file that retrieves data from table "clients" and shoots out an output in XML format:PHP Code:

<?php    /* *************************************  Retrieve data from DataBase with Flash CS3                   http://www.flepstudio.org       Author: Filippo Lughi            version 1.0                                 ************************************* */ /******** CHANGE YOUR DATABASE SETTING *******/    $dbhost = 'localhost'; // database host ( usually localhost )    $dbuser = 'root'; // database username    $dbpass = 'root'; // database password    $dbname = 'dbname'; // database name    $mysql = mysql_connect($dbhost,$dbuser,$dbpass);    mysql_select_db($dbname);        $Query="SELECT * from clients";    $Result=mysql_query( $Query );    $Return="<?xml version=".'"1.0"'." encoding=".'"UTF-8"?>'."\n"."<clients>";        while($client=mysql_fetch_object($Result))    {     $Return.="<client><id><![CDATA[".$client->ID."]]></id><name><![CDATA[".$client->name."]]></name><surname><![CDATA[".$client->surname."]]></surname><address><![CDATA[".$client->address."]]></address><city><![CDATA[".$client->city."]]></city><state><![CDATA[".$client->state."]]></state><email><![CDATA[".$client->email."]]></email></client>"; 

    }    $Return.="</clients>";    mysql_free_result($Result);    echo ($Return);?>

Following is the output that PHP creates:HTML Code:

<?xml version="1.0" encoding="UTF-8"?><clients>

<client><id>1</id><name>filippo</name><surname>lughi</surname><address>piazza fiorentini 17</address><city>cesenatico</city><state>italy</state><email>[email protected]</email>

</client><client>

<id>2</id><name>paolo</name><surname>rossi</surname><address>via verdi</address><city>milano</city><state>italy</state><email>[email protected]</email></client>

<client><id>3</id><name>giacomo</name><surname>leopardi</surname><address>via marrone</address><city>roma</city><state>italy</state><email>[email protected]</email>

</client><client>

<id>4</id><name>antonio</name><surname>gialli</surname><address>via viola</address><city>napoli</city><state>italy</state><email>[email protected]</email>

</client><client>

<id>5</id><name>andrea</name><surname>viola</surname><address>piazza la bomba e scappa</address><city>torino</city><state>italy</state><email>[email protected]</email>

</client><client>

<id>6</id><name>paolo</name><surname>de paoli</surname><address>via paolino</address><city>paolopoli</city><state>italy</state><email>[email protected]</email>

</client><client>

<id>7</id><name>alessandro</name><surname>magno</surname><address>via da roma</address><city>roma</city><state>italy</state><email>[email protected]</email>

</client><client>

<id>8</id><name>briana</name><surname>banks</surname><address>via del padulo</address><city>genova</city><state>italy</state><email>[email protected]</email>

</client><client>

<id>9</id><name>ruggero</name><surname>ruggeri</surname><address>via del rug</address><city>ragusa</city><state>italy</state><email>[email protected]</email>

</client></clients>

Now I create a FLA that contains a DataGrid component in the stage.

I create the Document Class, main.as: Code:

package{

import flash.display.*;import flash.events.*;import flash.net.*;import flash.xml.*;import fl.controls.ScrollPolicy;

public class Main extends MovieClip{

private var clients_array:Array=new Array();private var titles_array:Array;

public function Main(){

addEventListener(Event.ADDED_TO_STAGE,init);}

private function init(evt:Event):void{

removeEventListener(Event.ADDED_TO_STAGE,init);

titles_array=new Array('id','name','surname','address','city','state','email');

loadXML();}

private function loadXML():void{

var loader:URLLoader=new URLLoader();

loader.addEventListener(Event.COMPLETE,completeHandler);

var request:URLRequest=new URLRequest('http://www.flepstudio.org/swf/ImmagazzinareDati/recuperare/getData.php');

try {

loader.load(request);} catch(error:Error) {

trace('Impossibile caricare il documento.');}

}

private function completeHandler(event:Event):void{

var result:XML=new XML(event.target.data);var myXML:XMLDocument=new XMLDocument();myXML.ignoreWhite=true;myXML.parseXML(result.toXMLString());var node:XMLNode=myXML.firstChild;var n:int=node.childNodes.length;for(var i:int=0;i < n;i++){

var obj:Object=new Object();

for(var j:int=0;j < node.childNodes[i].childNodes.length;j++)

{if(j==0)

obj.id=int(node.childNodes[i].childNodes[j].firstChild.nodeValue);if(j==1)

obj.name=node.childNodes[i].childNodes[j].firstChild.nodeValue;if(j==2)

obj.surname=node.childNodes[i].childNodes[j].firstChild.nodeValue;if(j==3)

obj.address=node.childNodes[i].childNodes[j].firstChild.nodeValue;if(j==4)

obj.city=node.childNodes[i].childNodes[j].firstChild.nodeValue;if(j==5)

obj.state=node.childNodes[i].childNodes[j].firstChild.nodeValue;if(j==6)

obj.email=node.childNodes[i].childNodes[j].firstChild.nodeValue;}clients_array.push(obj);

}

populateDataGrid();}

private function populateDataGrid():void{

my_dg.rowCount=5;my_dg.columns=titles_array;my_dg.verticalScrollPolicy=ScrollPolicy.ON;for(var i:int=0;i < clients_array.length;i++){

my_dg.addItem(clients_array[i]);}

}}

}

We have 3 functions:loadXML that calls the PHP script.completeHandler that parse the XML output and insert data into Array.populateDataGrid that populate the datagrid by using the PHP output.

Storing data in DataBase with Flash CS3

Often happens that we are developing a website with Adobe Flash to a client and / or friend and it's required to store the data of users via a form.

How to do?

This tutorial will try to explain to less experienced how to enter data into a database ( mySQL) by Flash.

First we need to reaffirm the notion that Flash and mySQL can not communicate directly. Need a server-side scripts (in this case PHP) that receives data from Flash and then insert them in the database. I've created an example using a form in Flash that sends data to a PHP script (name, first name, address, city, state, email) which in turn will store them in the database.

First of all we must create a new table in our DB: in this case a table called "clients" with 7 columns (ID, name, surname, address, city, state, email).

The file. Sql to create the necessary table is as follows:PHP Code:

CREATE TABLE `clients` ( `ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , `name` TEXT NOT NULL , `surname` TEXT NOT NULL , `address` TEXT NOT NULL , `city` TEXT NOT NULL , `state` TEXT NOT NULL , `email` TEXT NOT NULL ) ENGINE = MYISAM ; 

I create a form in Flash as follows: -- Six static text fields that contain the titles (name, surname, address, city, state, email) -- Six input text fields in which the user will insert his informations-- A dynamic text field that will display any messages for user (for example if it has not completed all fields) -- A button for sending data

Here it is:

The Document Class ( Main.as ) contains the following code:Code:

/* ************************************* * Data Store Flash CS3 + PHP * http://www.FlepStudio.org * Author: Filippo Lughi * version 1.0 ************************************* */package org.FlepStudio{

import flash.display.*;import flash.events.*;import flash.text.*;import flash.utils.*;import flash.net.*;import caurina.transitions.Tweener;

public class Main extends MovieClip{

private var email_checker:CheckEmail;

private var timer:Timer;

private var film_mc:MovieClip;

public static var _Name:String;public static var _Surname:String;public static var _Address:String;public static var _City:String;public static var _State:String;public static var _Email:String;

public function Main(){

addEventListener(Event.ADDED_TO_STAGE,init);}

private function init(evt:Event):void{

removeEventListener(Event.ADDED_TO_STAGE,init);

form_mc.x=stage.stageWidth+10;

stage.frameRate=31;

email_checker=new CheckEmail();

moveInForm();addButtonListener();

}

private function moveInForm():void{

Tweener.addTween(form_mc,{x:stage.stageWidth/2-form_mc.width/2,time:0.7,transition:"easeOutElastic"});

}

private function addButtonListener():void{

form_mc.send_btn.addEventListener(MouseEvent.MOUSE_DOWN,checkFields);}

private function checkFields(evt:MouseEvent):void{

if(email_checker.initCheck(form_mc.email_txt.text)){

if(form_mc.name_txt.text!=''&&form_mc.surname_txt.text!=''&&form_mc.address_txt.text!=''&&form_mc.city_txt.text!=''&&form_mc.state_txt.text!='')

{showWorking();_Name=form_mc.name_txt.text;_Surname=form_mc.surname_txt.text;_Address=form_mc.address_txt.text;_City=form_mc.city_txt.text;_State=form_mc.state_txt.text;_Email=form_mc.email_txt.text;

var send_data:StoreData=new StoreData(this);

}else

displayError("fill in all the fields please");

}else

displayError("invalid e-mail");}

private function displayError(s:String):void{

form_mc.error_txt.text=s;hideError();

}

private function hideError():void{

timer=new Timer(2500,1);timer.addEventListener(TimerEvent.TIMER,deleteError);timer.start();

}

private function deleteError(evt:TimerEvent):void{

form_mc.error_txt.text='';}

private function showWorking():void{

film_mc=new MovieClip();film_mc.graphics.beginFill(0xFFFFFF,0.7);

film_mc.graphics.drawRect(0,0,stage.stageWidth,stage.stageHeight);addChild(film_mc);

}

public function hideWorking():void{

removeChild(film_mc);

displayError("Data has been stored");

reset();}

private function reset():void{

form_mc.name_txt.text='';form_mc.surname_txt.text='';form_mc.address_txt.text='';form_mc.city_txt.text='';form_mc.state_txt.text='';form_mc.email_txt.text='';

form_mc.x=stage.stageWidth+10;

moveInForm();}

}}

At the following line:var send_data:StoreData=new StoreData(this);

I instance a new class with name StoreData, this class will send data to PHP.It's the following code: Code:

/* ************************************* * Data Store Flash CS3 + PHP * http://www.FlepStudio.org * Author: Filippo Lughi * version 1.0 ************************************* */package org.FlepStudio{

import flash.events.*;import flash.net.*;import flash.display.MovieClip;

public class StoreData{

private var request:URLRequest=new URLRequest('http://www.flepstudio.org/swf/ImmagazzinareDati/storeData.php');

private var _fla:MovieClip;

public function StoreData(fla:MovieClip){

_fla=fla;

sendToPHP();}

private function sendToPHP():void{

var variables:URLVariables=new URLVariables();variables.name=Main._Name;variables.surname=Main._Surname;variables.address=Main._Address;variables.city=Main._City;variables.state=Main._State;variables.email=Main._Email;request.method=URLRequestMethod.POST;request.data=variables;var loader:URLLoader=new URLLoader();loader.dataFormat=URLLoaderDataFormat.VARIABLES;addListeners(loader);trace(variables);try {

loader.load(request);} catch (error:Error)

{trace('Unable to load requested document.');

}}

private function addListeners(d:IEventDispatcher):void{

d.addEventListener(Event.COMPLETE,onComplete);}

private function onComplete(e:Event):void{

var loader:URLLoader=URLLoader(e.target);var vars:URLVariables=new URLVariables(loader.data);if(vars.answer=="ok"){

_fla.hideWorking();}

}}

}

The PHP file:PHP Code:

<?php     /*  *************************************   Flash CS3 Data Store Form                      http://www.flepstudio.org        Author: Filippo Lughi             version 1.0                                  *************************************  */  /******** CHANGE YOUR DATABASE SETTING *******/     $dbhost = 'localhost'; // database host ( usually localhost )     $dbuser = 'root'; // database username     $dbpass = 'root'; // database password     $dbname = 'name'; // database name     $mysql = mysql_connect($dbhost,$dbuser,$dbpass);     mysql_select_db($dbname);          /* VARIABLES FROM FLASH */     $name=$_REQUEST["name"];     $surname=$_REQUEST["surname"];     $address=$_REQUEST["address"];     $city=$_REQUEST["city"];     $state=$_REQUEST["state"];     $email=$_REQUEST["email"];          /*INSERT INTO DB*/     $Query = "INSERT INTO `".$dbname."`.`clients` (`ID`, `name`, `surname`, `address`, `city`, `state`, `email`) VALUES (NULL, \"".$name."\", \"".$surname."\",\"".$address."\",\"".$city."\",\"".$state."\",\"".$email."\");";          /* ECHO TO FLASH */

    if(mysql_query($Query))     {         $answer='ok';         echo "answer=".$answer;     }     else     {         $answer='nope';         echo "answer=".$answer;     } ?>

FLASH, PHP dan MySQL

Ini mungkin basi bagi mereka yang udah bergelut di bidang animasi, terutama flash yang berhubungan dengan database dalam hal ini MySQL. Terus terang saya baru mencoba-coba mengkoneksikan aplikasi flash saya dengan MySQL dengan bantuan PHP. Ini merupakan tutorial dasar bagaimana mengkoneksikan Flash dan mengambil data dari MySQL yang akan ditampilkan di aplikasi Flash Anda. Kepada para suhu Flash mohon bantuannya kalau ada kesalahan dalam tutorial ini.

Yang dibutuhkan dalam tutorial ini antara lain:- Program Aplikasi Macromedia Flash / Adobe Flash (Saya menggunakan Adobe Flash CS3)- Database MySQL (Saya menggunakan Mysql 5.0.24)- PHP (Saya menggunakan PHP 5.1.4)- Web Server Apache (Saya menggunakan Apache 2.0.59)- Editor (Saya menggunakan Notepad)- Sudah kenalan dengan Flash, PHP dan MySQL

1. Go To Flash Stage

Buka dokument baru, buat sebuah Dynamic text fields (Text Tools) dengan nama variable varNama pada property. Kemudian convert to Symbol menjadi sebuah Movie Clip dengan nama bebas terserah Anda. Kembali ke text yang sudah menjadi Movie Clip, klik kanan kemudian pilih Action (Untuk mengetikan Action Script). Ketik Script di bawah ini:

onClipEvent (load) {// Load file php dari local server dengan mengirimkan variable namaloadVariables(“http://localhost/flash/koneksi.php?nama=supono”, this, “GET”);}

Flash kita udah beres, Sekarang kita bekerja ke MySQL

2. Next MySQL Database

Buat sebuah database dengan nama misalnya “taskdb”, kemudian buat tabel bernama flash dengan dua field yaitu nama dan nomor telepon setelah tabel dibuat, jangan lupa masukkan datanya.

CREATE DATABASE `taskdb`;CREATE TABLE `flash` (`nama` varchar(25) NOT NULL,`telepon` varchar(25) NOT NULL)INSERT INTO `flash` (`nama`, `telepon`) VALUES (‘Supono’, ’022291215821′);

3. Next PHP Script

Setelah di buat database nya pada step sebelumnya, saatnya untuk menyambungkan dengan menggunakan sebuah bahasa pemrograman yang bernama PHP. Secara umum, sama seperti biasa, yaitu koneksi ke database, kemudian pilih nama database kemudian query ke table dan tampilkan deh. Untuk mengirimkan ke Aplikasi flash yaitu dengan mengisi nama text field pada flash yang kita beri nama variable “varNama” diisi dengan hasil dari array database (lihat pada baris terakhir sebelum tanda kurung kurawal)

<?php//koneksi.php//tampilkan data atas nama supono//level: basic, by supono | http://supono.wordpress.com

if($_GET['nama']) {$link = mysql_connect(“localhost”, “root”, “vertrigo”)or die(“<b>error</b>: koneksi ke database gagal”);$select_db = mysql_select_db(“taskdb”);$query = “SELECT * FROM flash WHERE nama=’”.$_GET['nama'].”‘”;$result = mysql_query($query)or die(“<b>error</b>: perintah query gagal <i>$query</i>”);mysql_close($link);$row = mysql_fetch_array($result);mysql_free_result($result);print “varNama=$row[nama] – ($row[telepon])”;}?>

Building a CRUD application using Java 6 Web Services and Flash Builder 4

Java SE 6 has built-in support for web services thanks to JAX-WS 2.0. Armed with nothing more than JDK 6, you can easily publish or consume a web service. This makes it really easy for a developer to prototype and quickly get started with web services. Using the data-centric features in Flash Builder 4, a web service can be easily introspected and accessed. In this article, I will build an end-to-end simple CRUD application in Java and Flex 4, where the Java methods are exposed as web service operations.

Java 6 Goodness

On the java side, all you need for this article is JDK 6 and optionally the mysql connector JAR if you want to run the final application.

To look at the complete Java code, download BookService.java and Book.java. The sample uses a simple mysql table called Books:

CREATE TABLE Books( BOOK_ID SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, BOOK_NAME VARCHAR(400) NOT NULL, BOOK_PRICE FLOAT NOT NULL, BOOK_AUTHOR VARCHAR(400) NOT NULL, PRIMARY KEY (BOOK_ID));

INSERT INTO Books ( BOOK_NAME, BOOK_PRICE, BOOK_AUTHOR ) VALUES ( 'Midnight''s Children', 250, 'Salman Rushdie')INSERT INTO Books ( BOOK_NAME, BOOK_PRICE, BOOK_AUTHOR ) VALUES ( 'Shame', 225, 'Salman Rushdie');INSERT INTO Books ( BOOK_NAME, BOOK_PRICE, BOOK_AUTHOR ) VALUES ( 'To Kill a Mocking Bird', 250, 'Harper Lee');INSERT INTO Books ( BOOK_NAME, BOOK_PRICE, BOOK_AUTHOR ) VALUES ( 'The Colour of Magic', 250, 'Terry Pratchett');

To expose your Java class as a web service, simply:

1) Annotate your Java class with @WebService, @WebMethod.

package com.sample;

import com.sample.Book;import javax.jws.WebService;import javax.jws.WebMethod;import javax.jws.soap.SOAPBinding;import javax.xml.ws.Endpoint;

@WebService@SOAPBinding(style = SOAPBinding.Style.RPC)

public class BookService {

@WebMethod public int addBook(Book book) { /* insert book into db */ int resultCode = 0; Connection connection = null;/* code omitted for brevity */

2) Use the Endpoint class in main()

public static void main(String[] args) { // create and publish an endpoint BookService bookservice = new BookService(); Endpoint endpoint = Endpoint.publish("http://localhost:8080/books", bookservice); }

3) Create a directory called generated and run apt (Annotation Processing Tool):

apt -cp .;mysql.jar -d generated com\sample\BookService.java

4) Run your class:

java -cp generated;mysql.jar com.sample.BookService

That's it, you have a web server running on localhost:8080 and you can access the WSDL by navigating to http://localhost:8080/books?wsdl

Flash Builder 4 Magic

Accessing the WSDL in Flash Builder 4 to build a Flex application is a snap.

1) Get Adobe Flash Builder 4 Beta 2 from Adobe Labs if you haven't already.

2) Create a new Flex Project, type in a project name and hit Finish.

3) In the bottom part of Flash Builder, choose the Data/Services tab and click on "Connect to Data/Service".

4) Pick Web Service, hit Next.

5) Paste the WSDL URL http://localhost:8080/books?wsdl as the "WSDL URI" and hit Finish.

6) Flash Builder 4 will introspect the WSDL and show you a list of operations you can select. Hit Finish.

Wiring it to a Flex UI

1) Start off by replacing your main MXML file with the following code:

<?xml version="1.0" encoding="utf-8"?><s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"

xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/halo"

minWidth="1024" minHeight="768"><s:Panel title="Books" x="61" y="78" width="124" height="387"> <s:List id="list" x="0" y="10" width="100%" height="100%"

borderVisible="false"></s:List></s:Panel><s:Panel title="Book Info" x="193" y="78" width="379" height="387"> <mx:Form x="0" y="10" width="377" height="300"> </mx:Form> <s:HGroup x="66" y="309"

height="46" verticalAlign="middle" contentBackgroundColor="#938F8F">

<s:Button label="Add" id="button" /> <s:Button label="Update" id="button2" /> <s:Button label="Delete" id="button3" /> <s:Button label="Get" id="button4" />

</s:HGroup></s:Panel></s:Application>

You should now have a UI that looks this in design view:

2) Switch to design view. Select the list in the "Books" panel. Right click the list and choose "Bind to Data".

3) Choose "New service call" and select the operation as getBooks(). Choose "Bind to field" as name.

4) Now select the form in the "Book Info" panel, right click it and choose "Bind to Data." Choose "Data type" in the "Generate form for" drop down. Hit Next.

You can choose the ordering of values in the wizard.

The generated form by default is bound to a value object with name "book."

5) Right click the list in the "Books" panel and choose "Generate Change Handler." The view will shift to source code and type in the following code into the change event handler:

/* point book to the selected item */book = list.selectedItem as Book;

This is done so that every time the selected changes in the list, the form on the right is updated. If you run the application now, it should get the list of books from the server.

6) To make sure the first item in the list is selected every time the list is retrieved from the server, add a "result" event handler to the CallResponder that fetches the data in your main MXML file.

<s:CallResponder id="getBooksResult" result="list.selectedIndex=0"/>

CRUD

Getting the Add/Update/Delete/Get buttons to work is painless:

1) Select the Add button in design view.

2) Right click, choose "Generate Service Call" and choose the addBook operation.

3) The IDE automatically switches to source view so that you can type in the parameter to the addBook operation. Simply type in book

protected function button_clickHandler(event:MouseEvent):void{ addBookResult.token = books.addBook(book);}

4) Repeat steps 1 - 3 for the update and delete buttons. The delete button uses an integer parameter, book.bookid instead of book.

5) Right click the "Get" button and choose "Generate Click Handler." In the event handler, call the list's creation complete method.

protected function button4_clickHandler(event:MouseEvent):void{ list_creationCompleteHandler(null);}

6) Optionally you could call list_creationCompleteHandler(null) after add, update and delete so that the list on the left is refreshed.

That's it, you have a CRUD app working! You can download the complete MXML file here.