Learn how to use Flash with PHP and MySQL

Hi all, sorry it took me so long to write this tutorial :frowning:

Well, here I go… :rambo:

[color=blue]Section 1: Introduction[/color]

So you want dynamic content on your Flash movie. Sounds simple, right? Well let me tell it is, and well, it isn’t. This tutorial assumes a basic knowledge of Actionscript, PHP and MySQL. If you have that, it’s time to move on. Otherwise, I recommend you do some reading on the subjects…

[color=blue]Section 2: Setting up your SWF to receive external data[/color]

Loading external data into an SWF is a fairly simple task. Although the external text file method is probably the most widely known, it is by far the clumsiest way to get data into your SWF. Of course, this may be your only option of your server doesn’t support MySQL/PHP! But for those of us who are fortunate to have these privileges, let me show you how Flash can get external data without having to create additional text files.

Dynamic text fields
In order for Flash to get data from an external source, you need to make use of dynamic text fields. Simply place a blank dynamic text field on the stage and make sure you give it a variable name (NB: dynamic text fields have both an instance AND a variable names. In this case we want to focus on the variable name). Note the name you give to the field’s variable name, as we’ll need it when we write our PHP script.

Once you have a text field setup, convert it to a movie clip symbol. Attach the following code to the resulting movie clip:


onClipEvent (load) {
/*assuming you have a personal web server and PHP installed locally*/
  loadVariables("http://localhost/test.php", this, "GET");
}

Ok, that’s probably the easiest part of all. Now on to the PHP.

[color=blue]Section 3: Writing the PHP script that will pass variables to your SWF[/color]

To pass a variable between PHP and you SWF, it is imperative that you know the name of the variable you want to populate within your SWF. Again, when I say variable name, I’m talking about a dynamic text field’s variable, not instance, name. As long as you keep that in mind, you should be alright.

The PHP script we’ll write is actually quite simple. All you need to do is use the print() function, whose output will be automatically passed to your SWF. As simple as this may seem, be warned that Flash needs to know which variable to populate with the data output from our script. In other words, we need to print the name of the variable attached to the dynamic text field we created earlier. This is a crucial step but is very simple to achieve. I’ve included an example below on how we would code this in PHP:


<?php
/*The value of $x would be printed to the screen but the SWF would not read the data*/
$x = "abc";
print $x;

/*The value of $x would be printed to the screen and because of the prefix 'myVar=', the SWF will //interpret this as being the intended value for the variable *myVar* in the SWF*/
print "myVar=$x";
?>

Like I said, simple concept but easy to forget.

If you’ve ever tried getting external data into your SWF from a text file, you’ll notice that the two methods are very similar. PHP has a great advantage though in that you can use things like arrays, loops and even functions with which you can access information from within a database. The last of which will be the focus for the rest of the tutorial :slight_smile:


Recap

  1. We have ourselves an SWF with a movie clip within which lies a dynamic text field, whose variable name is myVar.
  2. This movie clip has some code attached to it that loads a URL using the loadVariables() function.
  3. The PHP script located at the URL prints data to the screen, which is then read by the SWF and passed on to the dynamic text field with the variable name myVar.

[color=blue]Section 4: Setting up your MySQL table[/color]

Ok so our script doesn’t do much right now. All it does is pass our SWF a simple variable whose value is hard coded in the script. This is a tutorial on getting data dynamically from a database so, let’s move on to first setting up a table that will contain our information.

First of all, we must think about how our database will be organized. Text files are easy because they have a name and content, but how do we go about emulating that with a database? Simple. Take a look at the table below and you’ll understand what I mean.


MySQL table named *files*:

*------------------------------------------------*
| filename     | content                            |
*------------------------------------------------*
| myfile         | my file contents are here |
| anotherfile | some stuff here               |
*------------------------------------------------*

where filename is a varchar and content is a blob. This is the nice part. See how this is like a regular file system? It makes life simple as you can now execute queries like:


SELECT content FROM file WHERE filename='myfile';

Nice eh? Ok but I’m getting ahead of myself here. Before we move on to some more PHP, insert some dummy values in your database. So for example:


INSERT INTO files VALUES (
"testfile",
"test content. man i hope this works!"
);

Once you have successfully entered some data, it’s time to move on to the last step.

[color=blue]Section 5: Bringing everything together[/color]

Disregard the earlier PHP script we wrote and start off a fresh notepad session. The new script we will be writing will ultimately do three things.

[list]
[]Connect to our database
[
]Create an array of data from the database
[*]Print the array to the screen so that our SWF can read the data
[/list]

The first thing we need to do is make our script flexible. What I mean is, we want it to be able to read any file we tell it to, without having to re-write parts of the script. The easiest way to do this is by thinking of our new script as a function of sorts. That is, we will have the ability to send the file an argument (hence my analogy to a function) that will point to the file we want it to read. Sound difficult? Well it’s not, in fact, it’s the easiest part of this tutorial. To send an argument to a file all one needs to do is append a ? to the end of the URL, followed by the variable name, an equal sign and then the value we want the variable to contain*. For example:


http://localhost/test.php?x=my+value

*NB: This will only work if you have register_globals=on in your php.ini file. My server has them enabled but for some people it is a security issue. If your server does not have register_globals on, it is still possible to extract posted data using $HTTP_POST_VARS.

For simplicity’s sake, let’s name our new script read.php. Here’s what my script looks like:


<?php
/*read.php 
prints contents of content column where filename = $file*/

if($file) {
  $link = mysql_connect(dbhost, dbuser, dbpassword)
            or die("<b>error</b>: failed to connect to database");

  $query = "SELECT content FROM files WHERE filename='$file'";
  $result = mysql_query($query) 
              or die("<b>error</b>: failed to execute query <i>$query</i>");

  mysql_close($link);

  $desiredContent = mysql_fetch_array($result, MYSQL_ASSOC);

  mysql_free_result($result);

  print "content=$desiredContent[content]";
?>

You should note that the nature of the script assumes that the variable name of the dynamic text field is named content. Now, this can be a problem if you have several text fields in a single movie clip (i.e. you would have to name each field the same name, and that wouldn’t do you much good). The problem can be resolved though by adding a new variable to our script and by sending a second value via our URL. I’m not going to go through how this because 1)It’s fairly simple to do and 2)I have methods to my madness :).

Now back to Flash. Open the FLA we created earlier (the one with the lone movie clip with a dynamic text field in it), and modify the code attached to the movie clip so that it looks like this:


onClipEvent (load) {
  loadVariables("http://localhost/read.php?file=testfile", this, "GET");
}

Now publish the FLA and cross your fingers :). If all has gone well, you should see your text field filled with the text found in the content column of your database, where the file name is equal to testfile. If nothing shows up, there are a couple things I would recommend checking before you flame me for this tutorial not working :).

[list]
[]Make sure Apache (or other) is running if you’re doing this locally (ok I had to say this as it has happened to me in the past :slight_smile:
[
]Make sure the colour of the text in the text field is not the same as the background
[*]Make absolute sure that you gave the text field a variable name not an instance name
[/list]

If you still have problems and you don’t know why, don’t hesitate to reply to me directly or post a message.

[color=blue]Section 6: Conclusion[/color]

I admit it takes quite an effort to do something as simple as get information from a database into a Flash movie. I hope that you can understand the power of the database though, and how it can make your projects easier and more enjoyable to maintain. Maybe sometime in the future we could convince Macromedia to include functions that would interface directly with a database. Until that happens though, we’re gonna have to keep on scripting.

Yours,
ptolemy
[email protected]

Hey ptolemy,
Great tutorial! I’ll have this added along with a few others tomorrow (hopefully)!

Thanks!
Kirupa =)

cool! thanx this will help lol