AS3FlexDB Tutorial 1 : Connect to a MySQL Database

Tutorials about actionscript 3 and flex.

AS3FlexDB Tutorial 1 : Connect to a MySQL Database

Postby ghalex on Mon May 19, 2008 2:11 pm

1. Download and install AMFPHP 1.9
You can read Install & Test AMFPHP 1.9 if you don't know how.

2. Download AS3FlexDB
You can download AS3FlexDB from here.
Copy from AS3FlexDBKit.zip\src\FlexDB\services\ the "database.php" file and paste it into a new directory "mysql" in amfphp service directory.

3. Prepare Adobe Flex
- Create a new Flex Project: "FlexDBTutorial".
- Copy as3flexdb_version.swc file from AS3FlexDBKit-version.zip\bin folder into your "libs" folder.
- Copy services-config.xml from AS3FlexDBKit-version.zip\src\FlexDBTests\src folder into your project folder.

If you done everything ok you project must look like this:
Image

4. Setup services-config.xml
- Open services-config.xml
- Search for "http://localhost/amfphp/gateway.php" and replace this with your link to gateway.php file. If you have follow
the steps from Install & Test AMFPHP 1.9 this link should be fine and you don't have to change nothing.
- Right click on your Flex Project and in Flex Compiler paste -services "services-config.xml" and click ok.
Image

And we are done with all the configuration we have to do, now let's code !

5. Add a datagrid and connect to MySQL
- First of all lets add a datagrid to our application and a button. This is the code
for our datagrid and our button:
Code: Select all
 
<mx:VBox width="100%" height="90%">
<mx:DataGrid id="dataGrid" width="100%" height="100%" dataProvider="{users}" selectable="true">
   <mx:columns>
      <mx:DataGridColumn dataField="fname" headerText="First Name"/>
      <mx:DataGridColumn dataField="lname" headerText="Last Name"/>
   </mx:columns>
</mx:DataGrid>
<mx:Button label="Load from Database" click="onBtnClick()" />
</mx:VBox>
 


Now let's import the classes that we will use and create two variables that we will
use for manage database and query's:
Code: Select all
 
/** Database */
import phi.interfaces.IQuery;
import phi.interfaces.IDatabase;
import phi.db.Database;
import phi.db.Query;
/** */
 
private var db       :IDatabase;
private var query    :IQuery;
 


This is the datagrid source:
Code: Select all
 
[Bindable] public var users   :ArrayCollection;
 


Now let's connect to MySQL :
Code: Select all
 
/**
* This will be call when Application creation
* has complete.
*/

private function onCreateComplete():void
{
   db = Database.getInstance();
   query = new Query();
 
   db.connect("conn1", "root", "", "localhost", "flexdb", true);
   query.connect("conn1", db);
 
}
 


I have create a table "users" for test. So we will query our database and select all users in this table.
The table has this structure:
Code: Select all
 
CREATE TABLE `users` (
`id` INT( 5 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`fname` VARCHAR( 255 ) NOT NULL ,
`lname` VARCHAR( 255 ) NOT NULL
) ENGINE = innodb;
 


and the code for select all users in this table is:
Code: Select all
 
private function onBtnClick():void
{
   query.addEventListener(Query.QUERY_END, queryEnd);
   query.execute("SELECT * FROM users WHERE 1");
}
 
private function queryEnd(evt:Object):void
{
   users = query.getRecords();
}
 


And we are done :) !
Image

You can download the Flex project from below and if you have any questions post them here.
Attachments
FlexDBTutorial.zip
(1012.57 KiB) Downloaded 891 times
User avatar
ghalex
 
Posts: 28
Joined: Thu May 08, 2008 7:25 am

Re: FlexDB Tutorial 1 : Connect to a MySQL Database

Postby webmedica on Wed Jul 16, 2008 8:19 pm

Great tutorial. I have zero Flex experience before this, and I managed to get this going.

Some observations:

1. Your format is clean and much easier to read than many/most tutorials. Great job.

2. Adding SQL for the tables, and inserting minimal real world data via script would be good. Also, its easier to understand things like "name" and "phone" and "email" than more codelike names. This is a global problem with developers writing tutorials ;-)

3. It was not totally obvious to move the phi directory into the project folder for a noob, you might call that out.

4. Crossdomain policies suck and some reference or a linked tutorial explaining them would be smart. Adobe's posted policies actually made me very more confused.

5. Also, (you will find this funny) you might point out how running in the IDE allows certain exchange of data from remote sites, so user understands they can work against remote data - setting up local mySQL can be cumbersome if its pre-existing and not small. Common issue and much relief that it works in IDE, as in Flash CS3. I hit "Run" by accident on the player files after watching hours of cross-domain errors and was shocked to see it run and work inside the center pane! Much time lost and hair torn out!

6. Since I see you porting tutorials, Oscar Trelles version of AMFPHP for Flash CS3 might be a good candidate, it makes a nice companion piece to this one.

7. FB3 put stuff in slightly different folders, and I had to move the services-config into src to get it to compile. Total noob stuff I know, but that's your main audience.

Awesome site, hope to see more material here.

Thanks,
Chris
webmedica
 
Posts: 1
Joined: Wed Jul 16, 2008 8:01 pm

Re: FlexDB Tutorial 1 : Connect to a MySQL Database

Postby Ethernut on Wed Jul 30, 2008 9:53 pm

Hi Ghalex

I have been doing flex/amfphp development for a long time now, and Ialways hated manully coding the amfphp classes. This flexdb is absolutely the best thing since sliced bread. The concept has simplified my work tremendously.Thanks for the great tutorial.

I do have 2 questions though:

#1 : Your tut shows how to get info from a database. The event listener on the Query class then fires when it receives the result and the datagrid gets updated. The problem is that when I set the SQL statement to an insert, update or delete command, it clears the datagrid as the SQL result is then actually null (not a select)

#2 : How would I use the query class if I have a datagrid in a component and not in the main application. Would I reference it using Application.application after importing the mx.core.application classes? The project that I am working on will have about 9 components, so I do not want to open 9 database connections. I would like to re-use the same connection on the main application for each of the 9 datagrids in each component.
Ethernut
 
Posts: 1
Joined: Wed Jul 30, 2008 9:43 pm

Re: FlexDB Tutorial 1 : Connect to a MySQL Database

Postby ghalex on Fri Aug 01, 2008 11:10 pm

First I am very glad that some people like my work. Thanks for all the good words :D

Some news first:
#1. I have just upload a new version of AS3FlexDB (with a new cool preloader and some updates). Download here

Answers:
#2. Your answer to your first question try to make a class something like this :

Code: Select all
 
public class Playlists
{   
   // Database objects
   private var db         :IDatabase;
   private var query       :IQuery;
 
   private var table      :String = 'playlist';
   private var idUser      :Number = 0;
 
   private var playlists   :ArrayCollection = new ArrayCollection();
 
   public function Playlists()
   {
      db = Database.getInstance();
      query = new Query();
 
      query.connect(db.getDefaultConnectionName(), db);
      query.addEventListener(Query.QUERY_ERROR, queryError);
   }
 
   public function get Playlists():ArrayCollection
   {
      return playlists as ArrayCollection;
   }
 
   public function addPlaylist(playlist:Object):void
   {
      var arrInsert :Array = new Array();
 
      arrInsert.push({key: "id",        value: playlist.id});
      arrInsert.push({key: "titlr",   value: playlist.title});
 
      query.addEventListener(Query.QUERY_END, onComplete);
      query.arrayInsert(table, arrInsert);
   }
 
 
   public function load():void
   {
      query.addEventListener(Query.QUERY_END, loadComplete);
      query.execute("SELECT * FROM "+ table +" WHERE 1 ORDER BY id");
   }
 
   /**
    * After insert is complete we reload the playlists.
    */

   private function onComplete(evt:Event):void
   {
      query.removeEventListener(Query.QUERY_END, onComplete);
      load();
   }
 
   private function loadComplete(evt:Event):void
   {
      var row  :Object = new Object();
      var playlist :Object = new Object();
 
      playlists.removeAll();
      while(row = query.getRow())
      {
         playlist = new Object();
 
         playlist.id      = row.id;
         playlist.title   = row.title;
 
         playlists.addItem(plVO);
      }
 
      query.removeEventListener(Query.QUERY_END, loadComplete);      
   }
 
   private function queryError(evt:Event):void
   {
   }
}
 


and all you have to do is to point the datagrid provider to a playlistsObj.Playlists for ex.:

Code: Select all
 
var plObj : Playlists = new Playlists();
dataGridProviderArr = plObj .Playlists;
 


after that you can call plObj.load() or plObj.addPlaylist.

I hope this make things clear for your first question

#3. And for you second question try to organize your code into objects. For ex if you have a table products make a
object that cand add, delete and load products from that table in this way things will be much easy.
User avatar
ghalex
 
Posts: 28
Joined: Thu May 08, 2008 7:25 am

Re: FlexDB Tutorial 1 : Connect to a MySQL Database

Postby Mississippi on Tue Dec 30, 2008 2:03 am

Thanks for the lesson, I have implemented a little application based on your tutorial but am having problems with multiple queries clearing out previous queries even with different eventListeners and different arrayCollections. I am trying to make the calls in script versus mxml to be able to respond to user events.

I basically have a DataGrid (main-master) which when clicked opens a new master-detail component which requires queries for master and details. Pretty simple stuff, but I am very new to Flex and OOP in general. All the code is in the same application, if that matters.

Thanks again.
Mississippi
 
Posts: 1
Joined: Tue Dec 30, 2008 1:54 am

Re: FlexDB Tutorial 1 : Connect to a MySQL Database

Postby animike on Wed Dec 31, 2008 6:03 pm

This is some great stuff, thanks for putting it out here ... I am new to flex so I have been trying out different tools to connect flex to mysql, mostly for integration with joomla and wordpress and least for now while I learn the ropes. I have to say this beats out by a mile the regular methods of creating connections with amfphp ... please keep it up .. I am hoping by the time I really get good with flex I will also get flexdb lock down. thanks again.
animike
 
Posts: 1
Joined: Wed Dec 31, 2008 5:55 pm

Re: AS3FlexDB Tutorial 1 : Connect to a MySQL Database

Postby shanis42 on Mon Jan 19, 2009 2:15 am

I keep getting an error at runtime about:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at FlexDBTutorial/onBtnClick()[C:\Users\90Media\Documents\Flex Builder 3\FlexDBTutorial\src\FlexDBTutorial.mxml:46]
at FlexDBTutorial/___FlexDBTutorial_Button1_click()[C:\Users\90Media\Documents\Flex Builder 3\FlexDBTutorial\src\FlexDBTutorial.mxml:11]

What should I be looking for? I have AS3FlexDB and AMFPHP installed and running. But code is still kicking out a null error. Any ideas?

I get this error when running the code "Out of the box". What I am really looking to do is use a text field to send a parameter to the query, on your tutorial you have a button to load the records from a database with a SELECT ALL query. I am looking for the user to input a lastname and have that sent to the query on enter or button click. For example "SELECT * FROM users WHERE lname = 'txt_lname.text'" Once I get it working (around the 1009 error), I think I will need the onbtnClick function to handle a parameter and pass it to the function.

Any apologies in advance, I am a total Flex noob, I am a php guy looking to broaden my horizons. Thanks in advance.
shanis42
 
Posts: 1
Joined: Mon Jan 19, 2009 2:11 am

CAN'T Connect to MySQL Database

Postby matasoy on Mon Jan 19, 2009 11:30 am

shanis42, i have the same warning in Firefox. However there is not any warning in Explorer, swf couldn't work.

TypeError: Error #1009: Boş nesne başvuru özelliğine veya yöntemine erişilemiyor.
at FlexDBTutorial/onBtnClick()[C:\Users\Murat ATASOY\Documents\Flex Builder 3\FlexDBTutorial\src\FlexDBTutorial.mxml:39]
at FlexDBTutorial/___FlexDBTutorial_Button1_click()[C:\Users\Murat ATASOY\Documents\Flex Builder 3\FlexDBTutorial\src\FlexDBTutorial.mxml:10]



i really try to connect to MYSQL but i can't.
1) Open flex project and set the amfphp folder into my localhost folder.
2) Write code as you wrote. I wrote the connection, import, functions, .. etc. Setup the Db name, host, username and pass
3) Add the services-config.xml file to project->libs and change the way of gateway.php file
4) Create a DB and create users table. Add some datas in it.
5) From project properties, i changed the -locale en_US -services "services-config.xml"
6) Add the as3flexdb_1.4.0.swc in project->src folder.
7) Create a folder mysql in C:\Apache2Triad\htdocs\amfphp\services

When i start the Run button, the project start, i can see the swf file and grid and button but, when i click on it, i cant see any data. I check the connection datas and Db datas. There is nothng wrong.

I cant solve this problem. My Flex version 3.0.194161. I use Flash Cs4 and Player 10.

Please help me,
Thanks a lot
Rize University / Turkey
Lecturer Murat ATASOY
User avatar
matasoy
 
Posts: 2
Joined: Mon Jan 19, 2009 11:02 am

Re: AS3FlexDB Tutorial 1 : Connect to a MySQL Database

Postby ghalex on Tue Jan 20, 2009 8:16 am

I have check and the error was my fault. You and shanis42 get this error because query object is never initialized. I forgot to put :

Code: Select all
 
<mx:Application
   creationComplete="onCreateComplete()" // this is why you get that error
   xmlns:mx="http://www.adobe.com/2006/mxml">

 


And another thing that I have see is that :
3) Add the services-config.xml file to project->libs and change the way of gateway.php file (This is wrong services-config.xml must be in project->src )
6) Add the as3flexdb_1.4.0.swc in project->src folder. (This is wrong this must be in project->libs)

I hope this could help.
User avatar
ghalex
 
Posts: 28
Joined: Thu May 08, 2008 7:25 am

Re: AS3FlexDB Tutorial 1 : Connect to a MySQL Database

Postby bgarvida on Tue Jan 27, 2009 3:08 am

AS3FlexDB is great! I was able to get the tutorial to work in my localhost. However, when I move my database to my remote site and still do my flex development in my local machine, I get this error message when I click on the 'load from database' button: ArgumentError: Error #2004: One of the parameters is invalid. url: 'http:www.rmcdavao.com/amfphp/gateway.php'..

I am sure that the mysql database and amfphp are correctly set up in my remote site. My localhost is running with php 5.2.5 while my remote site is running php 4.4.6. Could this be the problem?

Thank you guys....
bgarvida
 
Posts: 2
Joined: Tue Jan 27, 2009 2:44 am

Next

Return to AS3/Flex Tutorials

Who is online

Users browsing this forum: No registered users and 1 guest

cron