Sei sulla pagina 1di 13

Integrating Flash with an Access Database By Matt Duckhouse

print this article

Rating: 4.2 out of 5 Rate this article

email this article to a colleague suggest an article

Overview

Macromedia's Flash is often only used to create those annoying Web site intros that people skip right past. Well, since the latest versions of Flash including the ability to interface with ASP and other server-generated Web pages you can now do much more.
BlackBerry Enterprise Server Express provides access to new administrative features, monitoring tools, and more. Learn how the features of BlackBerry Enterprise Server Express can help your company become more productive. Click on the boxes below for a report that addresses your needs.

Click on your choices:


Feature:
Information Protection IT Management and Support Productivity Tools

Company Size:
1-99 100-499 500-999 1000+

Job Title:
IT Manager Executive Information Worker

Microsoft SQL Server 2008 - Free Trial


Download the Free 180-day Trial of SQL Server 2008 Enterprise Edition! Microsoft.com/EverybodysBusiness

Reach Millions of Netbook Users


Easily create and sell netbook apps with the Intel Atom Developer program appdeveloper.intel.com

AutoCAD LT - 30-Day Trial

Professional Starts Here. See what AutoCAD LT 2011 Can Do for You. Autodesk.com/AutoCAD-LT

This article explains how to connect a Flash movie to an Access database, and use an ASP page to query the database and hand information over to the Flash movie. We are going to build a very simple Flash address book to demonstrate the technique. You are going to need a few tools to build the address book: Macromedia Flash 5, Internet Information Services 4.0 (or IIS 5.0), and a copy of Microsoft Access. You can both download all the source files and see the final product here. The Basics A Flash movie cannot query a database directly. It can, however, fetch an ASP page that, in turn, can query a database. This functionality revolves around using Flash's ActionScript function loadVariables, as follows:
loadVariables(URL, location);

The loadVariables function retrieves the contents of the URL specified and used this to set variables within the Flash movie. The content must be in Multipurpose Internet Mail Extension (MIME) format or (to get technical) application/x-www-urlformencoded. For instance, if the URL specified contains a page with the following content:
Var1=Test&Var2=Demo

The variable Var1 within the Flash movie would be set to "Test" and the variable Var2 would be set to "Demo." The variables can then be accessed through Flash ActionScript to modify the behavior of the movie. In our demonstration we are going to use this behavior to pass data to a Flash movie from an Access database that will be queried by an ASP page. Database Design First, let's build the database. Our address book is going to be pretty simple so the database only has a single table called "Contacts" with five fields: ContactID, Name, Telephone, City, and Notes. Field name ContactID Name Telephone City Notes Type AutoNumber Text Text Text Memo Size 50 50 50 -

The database is called "AddressBook.mdb" and is held in the same directory as the ASP and

Macromedia Flash File Format (SWF) files we are about to build. (SWF is the file format used by Macromedia Flash to deliver graphics, animation, and sound over the Internet. About 90 percent of Web users can view SWF content without having to install a plug-in.) ASP Design Let's take a look at the ASP page we will use to fetch
<% Set DataConn = Server.CreateObject("ADODB.Connection") DataConn.Open "Driver=Microsoft Access Driver (*.mdb);DBQ=" & Server.MapPath("AddressBook.mdb") Set cmdTemp = Server.CreateObject("ADODB.Command") Set rstContacts = Server.CreateObject("ADODB.Recordset") cmdTemp.CommandText = "Select * From Contacts" cmdTemp.CommandType = 1 Set cmdTemp.ActiveConnection = DataConn rstContacts.Open cmdTemp, , 1, 3 rstContacts.Move CLng(Request("Record")) Response.write "Name=" & Server.URLEncode(rstContacts("Name")) & "&" Response.write "Telephone=" & Server.URLEncode(rstContacts("Telephone")) & "&" Response.write "City=" & Server.URLEncode(rstContacts("City")) & "&" Response.write "Notes=" & Server.URLEncode(rstContacts("Notes")) & "&" Response.write "TotalRecords=" & rstContacts.RecordCount rstContacts.Close DataConn.Close %>

The page assumes that we pass in the record that we want back from the database and then it returns the information in MIME format using the Server.URLEncode command. A typical output from our ASP page might be:

Note: We output one extra piece of information (in addition to our information fields) from our ASP page - that is "TotalRecords." TotalRecords is a numerical variable holding the number of records in the address book. This will help our Flash movie know when it has reached the end of our address book. Our ASP page is called "GetDetail.asp" and will be saved in the same directory as our database and Flash files. Flash Design With our database and ASP page built to query it, we next to put together our Flash movie to produce the front end to our address book. Let's start off with a new movie and insert a blank movie clip into it. The movie clip is going to be our address book, and it will consist of five text fields (for us to display our information in) and two buttons (left and right arrows used to navigate through the records.) The address book looks a bit like this:

The text fields have been created as dynamic text and have each been given a variable name. This will allow us to control their contents from within ActionScript. Look at what happens when the movie clip is first loaded. We add an action to the clip to tell it to load up our ASP page with the first record as soon as it finishes loading. The ActionScript looks like this:
onClipEvent(load) { CurrentRecord = 0; loadVariables ("getdetails.asp?Record=0", this); }

It simply initializes our CurrentRecord variable (which we will use to keep track of our position in the address book) and then loads our GetDetails.asp page, which asks for the first record (i.e., Record 0). One of the features of the loadVariables function is that it does its stuff asynchronously. This means that after Flash has executed a loadVariables command, it doesn't hang around waiting for the results to come back. Therefore, the data hasn't necessarily been loaded by the time the program reaches the line following the loadVariables function. So we need a mechanism to tell the movie to update our text fields whenever the data has finally loaded in. To achieve this we use the onClipEvent(data) action. This action is called whenever Flash has finished loading a set of variables. Our ActionScript looks like this:
onClipEvent(data) { strName = Name; strTelephone = Telephone; strCity = City; strNotes = Notes; strPosition = "Record " add String(CurrentRecord+1) add " of " add String(TotalRecords); }

This code simply transfers the variables retrieved from the ASP page into the text boxes that we added to our movie clip. It also updates a text field to show which record we are currently displaying. Finally, we need to assign actions to the left and right arrows so we can navigate through the address book. Here's the code for the right (move to next record) arrow:
on (release) { CurrentRecord++; if (CurrentRecord == TotalRecords) CurrentRecord = 0; loadVariables ("getdetails.asp?Record=" add String(CurrentRecord), this); }

This code increases the CurrentRecord variable by 1 and checks to see whether we have gone past the last record in the address book. If we have, CurrentRecord is reset to 0, and the user is sent back to the first record in the address book. The code next loads the variables associated with the record from the ASP page. When the record has been loaded, Flash will call the onClipEvent(data) action again, and this will update the text boxes our users see. The code for the left (move to previous record) arrow is virtually the same, except that we are decreasing the current record rather than increasing it. And that's all we need to do. When we launch the SWF file from a browser, it will load the first

record into Flash variables within the onClipEvent(load) action. After the variables have been loaded, Flash will call the onClipEvent(data) action, where we update our text fields to display the information to our user. Clicking on either navigation button will trigger actions that retrieve our ASP page and load in the new record, again calling on the onClipEvent(data) action. Here is how the final product looks:

Conclusion By combining the capabilities of Flash and ASP it's possible to create solutions that unite the graphical appeal of Flash with the data-retrieval capabilities of ASP. In this demonstration, we showed how it is possible to connect a Flash movie to an Access database. However, modifications to the ASP code would allow us to connect to an SQL server or any other data source for that matter. About the Author

Matt Duckhouse lives and works in the United Kingdom. At DCS Automedia, the eBusiness solutions division of DCS Automotive, he develops Internet solutions for the automotive industry. Currently, he is working on a number of computer-based training systems, many of which are delivered over the Web using Flash to improve the presentation, while still maintaining content in a database. He can be reached at mattduckhouse@yahoo.co.uk.

n(press){ loadVariablesNum("ProcessForm.asp",0,"post"); } On my ASP file there is the following code... <%@language = "VBScript" %> <% strFirst = Request.Form("Fname") strLast = Request.Form("Lname") strEmail = Request.Form("Email") strMessage = Request.Form("Message") Response.Write(strFirst) & "<br>" Response.Write(strLast) & "<br>" Response.Write(strEmail) & "<br>" Response.Write(strMessage) MyPath=Server.MapPath("Contact.mdb") Set conn = Server.CreateObject("ADODB.Connection") ' conn.Open "Driver={Microsoft Access Driver (*.mdb)};" & _"DBQ=" & MyPath SQL = "INSERT INTO Contacts(FirstName, LastName, Email, Message) VALUES ('"&strFirst&"','"&strLast&"','"&strEmail&"','"&st rMessage&"')" conn.Execute(SQL) %>

4. Saving data to databases (php-asp-cfm code) When using databases, there are SO considerations that you need to take into account. Not all databases are available for different platforms and some of them are difficult to manage for nontechnical users. So we will give some examples, using Access trough asp or Coldfusion, and PHP using MySQL. While the first works on Microsoft or ColdFusion servers, the second could work in any platform. We don't give details about how to setup the database, you can see in the loading data tutorial about registering the Access database to Coldfusion, or this other about setup PHP and MySQL database (also download from there the Access database mdb file of the SQL script to create mysql table). The Flash-back-end talk is very similar to the text technique, that's the back-end language receive POST parameters and pass to the database. So steps are: 1. Setup database table(s) 2. Receive Flash parameters 3. Connect back-end language with database, query database and insert data 4. Write an OK or error message Example differs in back-end side, but Flash side is the same. Our table need to hold a table with 4 columns: a. Id, usually an autonumber as unique identifier of a row b. Title, text c. Comments, text d. Image, text As, exposed, the database setup was explained in the "Loading data tutorial". Back-end scripting Ok, good news: the Flash side is exactly the same as the text example. Let's change only the name of the file, so is more descriptive of the database operation:
submit.addEventListener("mouseDown", sendData) function sendData(evt:Event){ if(Title.text!="" && Comments.text !="" && Image.text!=""){ //for those using PHP var myData:URLRequest = new URLRequest("insert.php") //those using ColdFusion should use next line //var myData:URLRequest = new URLRequest("insert.cfm") myData.method = URLRequestMethod.POST var variables:URLVariables = new URLVariables() variables.Title = Title.text variables.Comments = Comments.text variables.Image = Image.text myData.data = variables var loader:URLLoader = new URLLoader() loader.dataFormat = URLLoaderDataFormat.VARIABLES

loader.addEventListener(Event.COMPLETE, dataOnLoad) loader.load(myData) } else status_txt.text = "All fields are mandatory"

Those using ColdFusion locally on port 8500, should use the complete path: var myData:URLRequest = new URLRequest("http://localhost:8500/insert.cfm") Here's again the screenshot of our form (check examples files or the text explanation to build the movie by yourself)

Let's begin with the CFM code.


<cfsetting enablecfoutputonly="YES"> <cfset Title = form.Title> <cfset Comments = form.Comments> <cfset Image = form.Image> <cfquery datasource="anastasio"> INSERT INTO Titles(Title, Comments, Image) VALUES ('#Title#', '#Comments#' , '#Image#') </cfquery> <cfset returnToFlash = "&writing=Ok&">

<!--- FlashOutput contains the string that will be sent back to Flash---> <cfprocessingdirective suppresswhitespace="Yes"> <cfoutput> #returnToFlash# </cfoutput> </cfprocessingdirective>

This page have only ColdFusion code. Name it insert.cfm and put into a Web server readable folder, Basically it receives the Flash parameters and use to insert into the Access database. Remember that you need to register the database to the ColdFusion server as anastasio (see loading data tutorial) And finally the PHP file
<?php

//Capture data from $_POST array $title = $_POST['Title']; $comments = $_POST['Comments']; $image = $_POST['Image']; //Connection to database $connect = mysql_connect("localhost", "root", "root"); mysql_select_db ("data", $connect); //Perform the query $result = mysql_query("INSERT into titles (Title, Comments, Image) values ('$title', '$comments', '$image')"); if($result) echo "writing=Ok&"; else echo "writing=Error"; ?>

Again, put the file into a server readable folder and change connection string to match your own (check loading tutorial for any doubt about what data to use in the connection string) Each back-end script change in the syntax of course, but all of them do the same: catch input from POST arguments, use it to insert into the database and return a success or fail message. That's it. IMPORTANT: Don't leave any space before the opening tag <?php or closing tag ?> or you will get an error!! Let's move to the last example using Remoting -----------------------------------------------------------------------------------TIP A common technique for debugging the back-end script is to open it directly into the browser to see if the output is as expected. So open the file trough your server, something like: http://localhost/insert.php (modify to match your own path) and see that the output is as the one

previous exposed. Remember to always do this prior to test your Flash movie: unexpected errors could break your script! Another useful technique is to use navigateToURL calls for debugging purposes anytime you load data. i.e.: navigateToURL(myData) //see the example to build the URLRequest sending the data This way, a new window with the PHP output opens, and you can see if all goes fine. After checking that, you simply delete the navigateToURL call ------------------------------------------------------------------------------------------

Potrebbero piacerti anche