Home > AMFPHP, ActionScript 3, Flash Platform > Flash CS3 DataGrid with AMFPHP & MySQL

Flash CS3 DataGrid with AMFPHP & MySQL

March 10th, 2008

Everyone seems to want to know what the simplest way is to populate a Flash CS3 DataGrid from AMFPHP and MySQL. This is trivial in Flex however I found that it was difficult in Flash Cs3 without a good understanding of AMFPHP. So here is the super simple example, plus a utility to help out.

First AMFPHP returns all AMF3 result resources as an ArrayCollection. This is great if you are working in Flex Builder. If you are working in Flash Cs3 AND you have not mapped your Flex library’s into Flash this is a problem.

Lets start by creating a MySQL database named products. Run the following SQL against the database to get a table Product and some data in the table. This is worth getting this database going as I am working on all the examples of remoting that mimic the BlazeDS quickstart guide!

CREATE TABLE `Product` (
  `PRODUCT_ID` int(11) NOT NULL auto_increment,
  `NAME` varchar(40) NOT NULL default '',
  `CATEGORY` varchar(40) NOT NULL default '',
  `IMAGE` varchar(40) NOT NULL default '',
  `PRICE` double NOT NULL default '0',
  `DESCRIPTION` varchar(255) NOT NULL default '',
  `QTY_IN_STOCK` int(11) NOT NULL default '0',
  PRIMARY KEY  (`PRODUCT_ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=19 ;

--
-- Dumping data for table `Product`
--

INSERT INTO `Product` VALUES(1, 'Nokia 6010', '6000', 'Nokia_6010.gif', 99, 'Easy to use without sacrificing style, the Nokia 6010 phone offers functional voice communication supported by text messaging, multimedia messaging, mobile internet, games and more.', 0);
INSERT INTO `Product` VALUES(2, 'Nokia 3100 Blue', '9000', 'Nokia_3100_blue.gif', 109, 'Light up the night with a glow-in-the-dark cover - when it is charged with light you can easily find your phone in the dark. When you get a call, the Nokia 3100 phone flashes in tune with your ringing tone. And when you snap on a Nokia Xpress-on gaming co', 99);
INSERT INTO `Product` VALUES(3, 'Nokia 3100 Pink', '3000', 'Nokia_3100_pink.gif', 139, 'Light up the night with a glow-in-the-dark cover - when it is charged with light you can easily find your phone in the dark. When you get a call, the Nokia 3100 phone flashes in tune with your ringing tone. And when you snap on a Nokia Xpress-on gaming co', 30);
INSERT INTO `Product` VALUES(4, 'Nokia 3650', '3000', 'Nokia_3650.gif', 200, 'Messaging is more personal, versatile and fun with the Nokia 3650 camera phone.  Capture experiences as soon as you see them and send the photos you take to you friends and family.', 11);
INSERT INTO `Product` VALUES(5, 'Nokia 6820', '6000', 'Nokia_6820.gif', 299.99, 'Messaging just got a whole lot smarter. The Nokia 6820 messaging device puts the tools you need for rich communication - full messaging keyboard, digital camera, mobile email, MMS, SMS, and Instant Messaging - right at your fingertips, in a small, sleek d', 8);
INSERT INTO `Product` VALUES(6, 'Nokia 6670', '6000', 'Nokia_6670.gif', 319.99, 'Classic business tools meet your creative streak in the Nokia 6670 imaging smartphone. It has a Netfront Web browser with PDF support, document viewer applications for email attachments, a direct printing application, and a megapixel still camera that als', 2);
INSERT INTO `Product` VALUES(7, 'Nokia 6620', '6000', 'Nokia_6620.gif', 329.99, 'Shoot a basket. Shoot a movie. Video phones from Nokia... the perfect way to save and share life’s playful moments. Feel connected.', 10);
INSERT INTO `Product` VALUES(8, 'Nokia 3230 Silver', '3000', 'Nokia_3230_black.gif', 500, 'Get creative with the Nokia 3230 smartphone. Create your own ringing tones, print your mobile images, play multiplayer games over a wireless Bluetooth connection, and browse HTML and xHTML Web pages.', 10);
INSERT INTO `Product` VALUES(9, 'Nokia 3120', '3000', 'Nokia_3120.gif', 159.99, 'Designed for both business and pleasure, the elegant Nokia 3120 phone offers a pleasing mix of features. Enclosed within its chic, compact body, you will discover the benefits of tri-band compatibility, a color screen, MMS, XHTML browsing, cheerful screen', 10);
INSERT INTO `Product` VALUES(10, 'Nokia 3220', '3000', 'Nokia_3220.gif', 199, 'The Nokia 3220 phone is a fresh new cut on some familiar ideas - animate your MMS messages with cute characters, see the music with lights that flash in time with your ringing tone, download wallpapers and screensavers with matching color schemes for the', 20);
INSERT INTO `Product` VALUES(11, 'Nokia 6680', '6000', 'Nokia_6680.gif', 222, 'The Nokia 6680 is an imaging smartphone that', 36);
INSERT INTO `Product` VALUES(12, 'Nokia 6630', '6000', 'Nokia_6630.gif', 379, 'The Nokia 6630 imaging smartphone is a 1.3 megapixel digital imaging device (1.3 megapixel camera sensor, effective resolution 1.23 megapixels for image capture, image size 1280 x 960 pixels).', 8);
INSERT INTO `Product` VALUES(13, 'Nokia 7610 Black', '7000', 'Nokia_7610_black.gif', 450, 'The Nokia 7610 imaging phone with its sleek, compact design stands out in any crowd. Cut a cleaner profile with a megapixel camera and 4x digital zoom. Quality prints are all the proof you need of your cutting edge savvy.', 20);
INSERT INTO `Product` VALUES(14, 'Nokia 7610 White', '7000', 'Nokia_7610_white.gif', 4500, 'The Nokia 7610 imaging phone with its sleek, compact design stands out in any crowd. Cut a cleaner profile with a megapixel camera and 4x digital zoom. Quality prints are all the proof you need of your cutting edge savvy.', 7);
INSERT INTO `Product` VALUES(15, 'Nokia 6680', '6000', 'Nokia_6680.gif', 219, 'The Nokia 6680 is an imaging smartphone.', 15);
INSERT INTO `Product` VALUES(16, 'Nokia 9300', '9000', 'Nokia_9300_close.gif', 599, 'The Nokia 9300 combines popular voice communication features with important productivity applications in one well-appointed device. Now the tools you need to stay in touch and on top of schedules, email, news, and messages are conveniently at your fingert', 26);
INSERT INTO `Product` VALUES(17, 'Nokia 9500', '9000', 'Nokia_9500_close.gif', 799.99, 'Fast data connectivity with Wireless LAN. Browse the Internet in full color, on a wide, easy-to-view screen. Work with office documents not just email with attachments and memos, but presentations and databases too.', 54);
INSERT INTO `Product` VALUES(18, 'Nokia N90', '9000', 'Nokia_N90.gif', 499, 'Twist and shoot. It is a pro-photo taker. A personal video-maker. Complete with Carl Zeiss Optics for crisp, bright images you can view, edit, print and share. Meet the Nokia N90.', 12);

Here is a very simple ProductService which has two methods. The constructor that creates the DB connection and GetProducts a select * result that returns all rows. Upload the ProductService.php file into your amfphp/classes directory. Check out the service in the AMFPHP Service Browser for fun and debugging your db connection!

class ProductService {

var $dbh;

public function __construct() {

   $this->dbh = mysql_connect ("localhost", "wade", "arnold") or die ('I cannot connect to the database because: ' . mysql_error());

mysql_select_db ("product");

}

function getProducts() {

return mysql_query(sprintf("SELECT * FROM Product"));

}

}

From Flash CS3 place a DataGrid on the stage and give it an instance name of products_dg. Place a button on the stage and give it an instance name of getProducts_btn and change the label to Get Products

Create a document Main.as class and link the new fla to the class. Copy the following code into the Main.as file and update the gateway url to your AMFPHP installation.

package {

 import flash.display.MovieClip;

 import fl.events.*;

 import flash.events.*;

 import flash.net.NetConnection;

 import flash.net.Responder;

 import fl.data.DataProvider;

 import ArrayCollectionDP;

 public class Main extends MovieClip {

 	private var gateway:String = "http://localhost/amfphp/gateway.php";

 	private var connection:NetConnection;

 	private var responder:Responder;

public function Main() {

 		getProducts_btn.addEventListener(MouseEvent.CLICK, sendData);

 		responder = new Responder(onResult, onFault);

 		connection = new NetConnection;

 		connection.connect(gateway);

}

public function sendData(e:MouseEvent):void {

 		connection.call("ProductService.getProducts", responder);

 	}

 	private function onResult(result:Object):void {

 		products_dg.dataProvider = ArrayCollectionDP.toDataProvider(result);

 	}

 	private function onFault(fault:Object):void {

 		trace(String(fault.description));

 	}

}

}

Create a new ActionScript 3 file called ArrayCollectionDP.as and copy the following code into it. This class is designed to convert an AS3 ArrayCollection into a dataprovider. This is necessary until Adobe adds by default ArrayCollection to Flash Cs3. I have no idea why this class is not part of Flash but I also don’t work at Adobe.

package {

 import fl.data.DataProvider;

 public class ArrayCollectionDP {

public static function toDataProvider(myArrayCollection:Object):DataProvider {

 		var values:Array = myArrayCollection.serverInfo.initialData;

 		var category:Array = myArrayCollection.serverInfo.columnNames;

 		var aArr:Array = new Array();

 		for (var i:Number=0; i < values.length; i++) {

 			aArr[i] = new Object();

 			for (var aIndex:* in category) {

 				aArr[i][category[aIndex]] = values[i][aIndex];

 			}

 		}

 		var dp:DataProvider = new DataProvider(aArr);

 	return dp;

 	}

 }

}

This class allows you to take the ArrayCollection result from AMFPHP and pass it through the class to get a DataProvider. The datagrid’s dataprovider can now be set simply.

You end up getting something that looks like this!

You should be able to take this example and start making your application right away. The ArrayCollectionDP.as class can be reused in the future! Let me know if this helps or of course if you get stuck. I will be using this example on amfphp.org soon with more details and of course all the source files!

AMFPHP, ActionScript 3, Flash Platform

  1. July 7th, 2009 at 07:22 | #1

    For those of you who have problems with datagrid database integration, look at this FlashDen Item:

    http://flashden.net/item/flash-to-mysql-dynamic-datagrid/29687

    PM admin@worldofrunes.com if you want a 25 %discount

  2. likish
    July 13th, 2009 at 11:55 | #2

    can someone pls upload a link to a php script that populates the datagrid from a data base or explain the TODO.

    I have my database returning into my AMFphp browser but i cant get the info into flash. I keep on getting the following errors

    TypeError: Error: Type Coercion failed: cannot convert [object Object] to Array or DataProvider.
    at fl.data::DataProvider/getDataFromObject()
    at fl.data::DataProvider/addItemsAt()
    at fl.data::DataProvider/addItems()
    at Main/onResult()

    If anyone could pls hepl me out it would be much appreciated as I have been trying to for a week.

    thanks

  3. August 30th, 2009 at 19:05 | #3

    @Thomas

    That’s a neat idea Thomas, but that is pretty risky sending SQL across the wire as XML, totally opening youself for SQL injection attacks.

  4. August 30th, 2009 at 19:09 | #4

    Thanks for the great tutorials Wade (including those provided with amfphp), I was brand new to php amfphp (1.9) and mysql, the progression from HelloWorld to this Example was great, though I had a few issues:

    1) View Source to get the Sql, if you can’t see it fully on this page. Copy it from there, else you might get errors trying to execute it.
    2) Copy the php from the webpage not the source, as “$this->dbh” gets escaped and causes php errors.
    3) you may have to replace double quotes as well.
    4) the ProductService.php file should be in the amfphp/services/ProductService.php not in amfphp/classes
    5) use a simple database test php prior to getting the actionscript. At least for me the wizard that sets up the database truncated the domainid prefix needed to actually connect.

    <?php
    mysql_connect(“localhost”, “SOMEDOMAIN_SOMEDBUSERID”, “SomeDBUSERIDPASSWORD”) or die(mysql_error());
    echo “Connection to the server was successful!”;

    mysql_select_db(“SOMEDOMAIN_SOMEDB”) or die(mysql_error());
    echo “Database was selected!”;
    ?>

  5. October 24th, 2009 at 17:45 | #5

    How can I pull my data from my database, run it through this script and only place certain fields from my database into the datagrid?

    I only need 3 columns in the grid but when clicked on, I need the rest of the data to do different things.

  6. Rodolfo
    November 1st, 2009 at 10:13 | #6

    Anyone resolve the order of columns in datagrid?…

    Thanks and let me know the way to do that…

  7. Mohammed
    December 21st, 2009 at 07:53 | #7

    can i edit directly at datagrid ?
    example:
    make datagrid editable from datagrid properties (component inspector)

    and when we insert value in datagrid
    automaticly updating the mysql database

    can we do that ????

  8. PixelMaker
    January 11th, 2010 at 15:26 | #8

    Hi,

    Thanks for sharing it.

    When I tried this one I got an error
    Main.as, Line 3
    1046: Type was not found or was not a compile-time constant: Simple Button
    import flash.display.MovieClip;

    Please help me to solve this.

    Thanks,
    -PM.

  9. Jonny D
    March 2nd, 2010 at 17:53 | #9

    @Andy Cook
    I have the same error… does anybody have a fix for this? Thanks

  10. SEM
    March 3rd, 2010 at 07:19 | #10

    Yo,

    I need some help.
    I put that code in AS in my .fla file

    var test:Main = new Main();
    var testo:ArrayCollectionDP = new ArrayCollectionDP();

    but i recieve that error. I’m probably doing something wrong. Can someone more experienced help me with this so i can run that datagrid?

    1120: Access of undefined property getProducts_btn.
    1120: Access of undefined property products_dg.

    Thanks

  11. Ricardo
    May 11th, 2010 at 09:02 | #11

    Thank you so much for this.

    That Class is very helpful.
    But I’ve been wondering if it was possible to change the name of the columns in Flash. I don’t want them to be named after their fields in the DB. But if I change their names manually, the data isn’t stored in the DataGrid. Do you have any thoughts on this?

    Once again, thanks for your work. :)

  12. September 8th, 2010 at 18:51 | #12

    You can dynamically change the names of the fields by altering your sql statement. For example:

    Select Name, Catagory, Image from Product

    can be changed to:

    Select Name as Customer, Catagory as BusinessLine, Image as Pic from Product

    Dynamically changing the field names, changes the column names in the grid.

  13. Davmaul
    October 7th, 2010 at 06:39 | #13

    @Ricardo
    Hi, why dont you change it using SQL Select order as:
    Select Product_id AS Identifier, QTY_IN_STOCK AS Stock FROM FROM Product

Comment pages
  1. March 11th, 2008 at 10:38 | #1
  2. November 25th, 2008 at 12:27 | #2