You are on page 1of 8

Samples.

GetMySQLData
Intro Send to PHP Receive from PHP Display in Flash Home About Sitemap

Database connectivity -- who can live without it? Since I've just succeeding in moving this site from an NT server (where it had an Access database and monstrous instability problems that I won't go into) to a Unix server with a MySQL database, it seemed like a good time to pass on some info on how to get Flash and PHP talking to each other to dump the contents of a MySQL database. Specifically, we'll look at how to send data from Flash to a PHP page, the PHP format to get the requested data back to Flash, how to check when the information we want from the database has been returned, and how to display it. The application I created is one which checks the log database to see who's visiting this site and what they're looking at. Log files started on October 8 and are available any day between then and now.
[Sorry, the Flash application has been temporarily removed from this page while the database which supported it is reconfigured. It is described in detail, including the flash source code, in the following pages.]

Variables Operators About Objects

MovieClip Object Date Object Color Object Math Object Sound Object XML Object

Here are the specific interactions in this app:


q

1 - (in Flash) Get a date and a number from the user, which will specify how many records to return, for which day 2 - (in Flash) Check that the date and number are both within an allowable range 3 - (in Flash) Send the information to the php page 4 - (in PHP) Query the database to find the total pageviews, visitors, and most-frequented pages for the given date 5 - (in PHP) Return a summary of that information to Flash 6 - (in Flash) Display the returned information

BubbleFloater ColorChanger LineDrawer PieChart TextScroller LoopMixer 3dRotator SlidingViewer MaskMover GetMySQLData TextAndFlash AttachMovie

Before we write any code to do those things, we have to define the structure of the movie. How many frames will we need, and what will go in each frame? Will variables be passed from the main timeline to the PHP page, or through a movieclip? The latter question is one we always answer with "movieclip", since that allows only the variables to be sent that we define (when a GET or POST is done from Flash to a server-side program, all variables in the timeline doing the operation will be sent). If we send from the main timeline, a bunch of extraneous variables will be sent needlessly to the PHP page. Sending via a movieclip also means that we can make use of onClipEvent(data) to check for data returned.

Other resources Q/A Archive SWF Studio Validation Routines

Credit

Define the structure of the movie


The "timeline" for this movie is extremely simple: one frame to get input from the user, another frame to display the results returned. The first is labelled "start" and the second "displaydata". Frame "start" has input textfields, a button to start the request, a dynamic textfield to display the current status, and a controller movieclip to do the actual sending and receiving of data (this clip continues into the

display frame also). Frame displaydata has several dynamic textfields for displaying the stats that are returned by php. Here are the contents of those frames:

Frame 1(-9): "start"

Frame 10(-20): "displaydata"

Put in code to initialize variables


In almost every Flash application, there is a need to initialize some variables. A good place to do this is in the frame actions of the first frame of the movie, which are executed before anything else in the movie, even before onClipEvent(load) routines on movieclips in frame 1. Our initialization code looks like this:
datavalues._visible = 0; ldom = [31,28,31,25,31,30,31,31,30,31,31,31]; // get current date values datenow = new Date(); daynow = datenow.getDate(); monthnow = datenow.getMonth(); // monthnow = 0-11 yearnow = datenow.getFullYear(); lastmonth = (monthnow==0 ? 11 : monthnow-1); // set default choosedate values // default to display yesterday's date chooseday = (daynow==1 ? ldom[lastmonth] : daynow-1); // display last month if current date is 1st of month choosemonth = (chooseday == daynow-1 ? monthnow+1 : lastmonth+1); // display last year if current date is Jan 1 chooseyear = ((daynow==1 && monthnow==0) ? yearnow-1 : yearnow); stop();

The first line of this code hides the datavalues movieclip, which holds the output fields, so that it won't show before data is available. (We put the textfields into a movieclip so that they would be available in the first frame to be filled in by our controller clip, but able to be made invisible to the user.) We also set up some date variables which we'll need for checking against the user's input. We set the default date to the previous day's date and stop in frame 1 to await user input. On the next page, we'll look at the steps to get that input and send it to a PHP page.
Intro Send to PHP Receive from PHP Display in Flash

Variables | Operators | Objects Movieclip Object | Date Object | Color Object | Math Object | Sound Object | XML Object Home | Samples | About | Sitemap | Resources | Credit | Contact

Samples.GetMySQLData
Intro Send to PHP Receive from PHP Display in Flash Home About Sitemap

Add code to get input from user, check it, pass it to PHP
Since we have a Stop action on frame 1, nothing happens in this movie til the user presses the "Show Me" button (presumably after filling in the date and number fields, but using the default values there if not). Thus the first thing the button should do is verify that the date and number entered are within range. Then, since we decided to send the data via a movieclip, we need to make sure the variables we want to send are defined in that movieclip. This is the code on the "Show Me" button. We set the status (error message) field blank to start, create date variables to do our comparison and then check the numbers the user entered. If an out of range value is found, a message is displayed. Otherwise, the datacontroller movieclip is given the variables we wish to pass to PHP, and its readySend flag is set to true.
on (release) { statusmsg = ""; // check for date between 10/8/2001 and now userdate = new Date(chooseyear, choosemonth-1, chooseday); startdate = new Date(2001, 9, 7); if (!(userdate - startdate > 0 && datenow - userdate > 0)){ statusmsg = "Enter a date between 10/8/2001 and " + (monthnow+1) + "/" + daynow + "/" + yearnow; } else { // check for number of records chosen between 5 and 10 if (!(thisnumber >= 5 && thisnumber <= 10)) { statusmsg = "Enter a number between 5 and 10"; } else { datacontroller.thismonth = choosemonth; datacontroller.thisyear = chooseyear; datacontroller.thisday = chooseday; datacontroller.thisnumber = thisnumber; datacontroller.readySend = 1; } } }

Variables Operators About Objects

MovieClip Object Date Object Color Object Math Object Sound Object XML Object

BubbleFloater ColorChanger LineDrawer PieChart TextScroller LoopMixer 3dRotator SlidingViewer MaskMover GetMySQLData TextAndFlash AttachMovie

Now let's look at what the datacontroller movieclip is doing. Basically, it's sitting doing nothing except checking the readySend flag to see when it's true. This is done with an onClipEvent(enterFrame) loop, of course. This is the code we put on the Object Actions of datacontroller in our first iteration of this movie:
onClipEvent (load) { readySend = 0; } onClipEvent (enterFrame) { if (readySend) { readySend = 0; _root.statusmsg = "Getting data..."; getURL ("checkdata.php", "_self", "POST"); } }

Other resources Q/A Archive SWF Studio Validation Routines

Credit

It checks for readySend true (which was set by the Show Me button), displays a message that it is going to get data (because that doesn't happen instantaneously and your user might like to know what's happening), and then does a getURL to a php page. Why a getURL and not loadVariables? Because we want to check and make sure our variables are being sent correctly before we continue development. So

we call checkdata.php using the POST method and specifying that the php page should open in the same window our Flash movie is currently running in. This is what checkdata.php looks like:
<?php $day = $HTTP_POST_VARS['thisday']; $number = $HTTP_POST_VARS['thisnumber']; $month = $HTTP_POST_VARS['thismonth']; $year = $HTTP_POST_VARS['thisyear']; echo "date read in: ".$month." ".$day." ".$year."<br>"; echo "number read in: ".$number; ?>

And the output in the browser window should look something like: date read in: 10 10 2001 number read in: 7 The next page looks at what php does with the data and how it is returned to Flash.
Intro Send to PHP Receive from PHP Display in Flash

Variables | Operators | Objects Movieclip Object | Date Object | Color Object | Math Object | Sound Object | XML Object Home | Samples | About | Sitemap | Resources | Credit | Contact

Samples.GetMySQLData
Intro Send to PHP Receive from PHP Display in Flash Home About Sitemap

Use variables passed to generate query, pass back string


We just saw how the php page reads the POSTed variables into php variables. Those variables are then used to construct SQL query strings to query the MySQL database and get the records we want. Those records are in turn converted, via a couple of for loops, into strings which Flash can read. In this sample, two queries are executed: one to return the number of page views per page per day, and one which returns a record for each unique visitor. The code excerpts below show how the returned data from each query ($qr) is converted to a string which will be passed back to Flash. The string must be of the form var1=value1&var2=value2 etc. Still using a getURL instead of loadVariables for the purposes of testing, we dumped the final return string to the browser window before trying to do anything with it in Flash. (Unless you are some kind of php superhero, using the echo command in php is as essential for debugging as using trace in Flash -- for everything from checking the format of the SQL query to various date calculations and any other intermediate steps along the way from reading variables to passing back a correctly formatted string. Only change your flash statement from getURL to loadVariables when you are certain all of these are correct.) The following code excerpts show how the string was generated and a sample of what was dumped to the browser window (though without carriage returns) on one of our tests:
<?php ... // get results of 1st query into variables thisPage0-thisPagen and thisCount0-thisCountn for ($i=0; $i<$nrows; $i++) { $row = mysql_fetch_array($qr); $pageCount += $row['pagesViewed']; if ($pagesCounted < $number) { $returnstring .= "&thisPage".$pagesCounted."=".$row['thisPage']." &thisCount".$pagesCounted."=".$row['pagesViewed']; $pagesCounted++; } } } // join previous results with results from visitors query to create final string $nrows = mysql_num_rows($qr); $returnstring = $returnstring."&userCount=".$nrows."&pageCount=".$pageCount; ... echo $returnstring; ?>

Variables Operators About Objects

MovieClip Object Date Object Color Object Math Object Sound Object XML Object

BubbleFloater ColorChanger LineDrawer PieChart TextScroller LoopMixer 3dRotator SlidingViewer MaskMover GetMySQLData TextAndFlash AttachMovie

Other resources Q/A Archive SWF Studio Validation Routines

Credit

This is the output from one of our tests:


returnstring: &thisPage0=sampletextscroller.php&thisCount0=110 &thisPage1=samples.php&thisCount1=104 &thisPage2=movieclipobject.php&thisCount2=91 &thisPage3=sampleslidingviewer.php&thisCount3=90 &thisPage4=sample3drotator.php&thisCount4=89 &thisPage5=samplebubblefloater.php&thisCount5=69 &thisPage6=samplelinedrawer.php&thisCount6=67 &userCount=389&pageCount=2121

Change code to pass variables and wait for response

Now that we know variables are successfully being sent from Flash to php and a correct string will be returned, we can modify our movie to send the variables, wait for a result to be sent back and then do something with it. The code on our datacontroller movieclip is changed accordingly:
onClipEvent (load) { readySend = 0; } onClipEvent (enterFrame) { if (readySend) { readySend = 0; _root.statusmsg = "Getting data..."; this.loadVariables("getdata.php","POST"); //getURL ("checkdata.php", "_self", "POST"); } } onClipEvent (data) { _root.gotoAndStop("displaydata"); }

We comment out the getURL line and instead use loadVariables. This tells Flash to send all variables defined for the current timeline (datacontroller) to getdata.php using the POST method, and wait for a response. When data is received from the php page, onClipEvent(data) will be automatically executed. When data is returned, we want to jump to the second section of our main movie, which begins in frame "displaydata". On the last page of this article, we'll look at what happens in the displaydata frame to display the results.
Intro Send to PHP Receive from PHP Display in Flash

Variables | Operators | Objects Movieclip Object | Date Object | Color Object | Math Object | Sound Object | XML Object Home | Samples | About | Sitemap | Resources | Credit | Contact

Samples.GetMySQLData
Intro Send to PHP Receive from PHP Display in Flash Home About Sitemap

Display the results in Flash


When the datacontroller movieclip sends control back to the main timeline (to frame "displaydata"), the only thing which has to be done is to fill the textfields on that frame with information that was passed to datacontroller. Data was returned to datacontroller because of the this.loadVariables("getdata.php","POST"); action executed from datacontroller. Executing this command as a method of the movieclip object means data is sent to php from this movieclip and returned from php to the same movieclip. Since we are displaying the number of hits per page for the most-frequently viewed pages, we went ahead and made the field an html formatted field so we could make it clickable. (If you view results for the current day, then click one of these links, then return and redisplay the results, you'll see it increment). Here is the code to fill in the pageurl and thisCount textfields in the datavalues movieclip, as well as the pageCount and visitorCount textfields on the main timeline:
for (i=0; i<thisnumber; i++) { datavalues["pageurl"+i] = "<font color=\"#66ccff\"><u><a href='"+ datacontroller["thisPage"+i]+"'>"+datacontroller["thisPage"+i]+"</a></u></font>"; datavalues["thisCount"+i] = datacontroller["thisCount"+i]; } pageCount = datacontroller.pageCount; visitorCount = datacontroller.userCount; datavalues._visible = 1;

Variables Operators About Objects

MovieClip Object Date Object Color Object Math Object Sound Object XML Object

The last statement sets the datavalues movieclip visible so the results can be seen.
Intro Send to PHP Receive from PHP Display in Flash

BubbleFloater ColorChanger LineDrawer PieChart TextScroller LoopMixer 3dRotator SlidingViewer MaskMover GetMySQLData TextAndFlash AttachMovie

Other resources Q/A Archive SWF Studio Validation Routines

Credit

Variables | Operators | Objects Movieclip Object | Date Object | Color Object | Math Object | Sound Object | XML Object Home | Samples | About | Sitemap | Resources | Credit | Contact