Você está na página 1de 42

Kristian Besley

Kristian Besley has worked with multimedia for 3 years but has been
doing creative work with computers for much longer. He currently
develops Flash-based material within an educational environment. This
material includes interactive presentations to illustrate how scientific
things work and GUIs/tools allowing web-based content creation with
basic computer skills. He was a contributing author for the seminal
book Flash Math Creativity and many other friends of ED books. In
2002 he launched the world’s first biannual HTML markup–based
TableArt competition. The competition was an unbelievable success.
ONLINE GAMING WITH PHP
AND MYSQL
FLASH MX 2004 GAMES MOST WANTED

So your game is pretty sweet and people are playing it online, but all the effort that they put in is unre-
warded because they can’t show anyone their impressively large score on it. What you need now is some
way to save the players’ names and scores, so they can boast to everyone else who plays it.

You can save user scores and names using a database and some server-side scripting. No, no, wait—don’t
close the book . . . come back! OK, so for most Flash designers the concepts of databases and server-side
scripting are pretty daunting, but the reality is that any fairly successful ActionScripter will be surprisingly
comfortable with it all.

The database will hold all your players’ scores, names, and other information, and the server-side scripting
is the code that will interpret that information and relay it to and from your Flash movie.

In this chapter, we’ll take you from the most basic dynamic task, loading in variables from a simple text file,
to a fully functional database-driven online high-score board. Although you might not know everything
inside out by the end, this chapter will open your eyes to the possibilities and hopefully take away that ini-
tial fear.

We’re going to use PHP as our server-side scripting language and MySQL as our database to help Flash cre-
ate the high-score table. There are other common server-side scripting languages (ColdFusion and ASP, to
name two) and other database options such as Microsoft Access and SQL Server, but the technologies
we’ve chosen here are free.

To save you a little frustration later on, you’ll need to download and install a
few packages. If this concept fills you with dread, remember that once you
have the packages, you’ll never need to download them again. The actual
downloads are listed a little later in this chapter, but you can go ahead and
read the first section without having to worry about these for now.

Dynamic Information in Flash


Before you start working with any server-side scripting or databases, it’s really worth getting a grasp of how
Flash imports data dynamically.

Beyond XML, JPEG, and MP3 loading, all data loaded into Flash is presented in the form of variables, little
named packages of information that Flash is ready to understand and display.

You might have seen something as ugly as this before:

&name=kristian&website=graphci.com&age=26&

If you’re already familiar with variables (from ActionScript maybe), what you see here is three variables:
name, website, and age. Here’s how it looks in a more traditional and less cryptic form:

name = kristian
website = graphci.com
age = 26

4
ONLINE GAMING WITH PHP AND MYSQL

In its code form, each of these variables is simply separated by an ampersand or & character. If you wanted
to add a fourth random variable and value to the end of the ugly string, it would look like this:

&name=kristian&website=graphci.com&age=26&instrument=guitar&

The way we prefer to see the variables or information with line breaks for
ease of understanding, Flash prefers to see it with ampersands dividing up
the variables. To each his own, but the information is still the same!

Let’s see how it works in practice by loading some variables into Flash from a standard text file. The files
for this exercise are available in the Chapter 9 code download and are called LoadVars01.fla and
my_data.txt.

Simple Dynamic Exercise


1. Open a standard plain text editor, such as Notepad (Windows), TextEdit (Mac OS X), or SimpleText
(Classic Mac). If you prefer (and have) something stronger, such as HomeSite or BBEdit, go ahead and
use it.

2. Type the following into your text editor:


&name=kristian&website=graphci.com&age=26&

Feel free to change this information to match your own personal information, but stick with the struc-
ture and variable names you see here.

&name=yourname&website=whatever.com&age=30&

3. Create a new folder somewhere on your hard drive and save the file as my_data.txt. Close the text file.
4. Open Flash and start a new movie. You need to attach some code to the first frame. So, in the Actions
panel, type the following:

inputData = new LoadVars ();

This line creates a new instance of the LoadVars object called inputData. This is used as a store for
variable data, and using LoadVars entitles you to make use of the various methods available to it,
specifically for working with dynamic input and output. These methods include load and sendAndLoad,
both of which you’ll use later in this chapter.

5. Before you go ahead and actually load in the variables from the text file, you need to set up actions to
run once the data has loaded. You do this with an onLoad event handler for the inputData LoadVars
instance like so:

inputData.onLoad = function () {
};

5
FLASH MX 2004 GAMES MOST WANTED

6. Now you need to fill up this function with instructions. Insert the following code between the curly
braces so the event and handler look like this:

inputData.onLoad = function () {
trace ("My name is " + inputData.name);
trace ("My website is " + inputData.website);
trace ("My age is " + inputData.age);
};

You could use this within the preceding handler instead of inputData, but
we’re using inputData to show you explicitly how it works and how the
LoadVars instance is used.

The code you’ve added here uses the imported variables name, website, and age. Because you’re load-
ing the variables from the text file into the inputData instance, you reference them in this form:

loadVarsInstance.variablename;

7. The last bit of code to add actually loads in the variables. Add this to the end of your code block:
inputData.load ("my_data.txt");

The load method does what it says on the tin: it loads in the variables from the specified data source.
All variables then retrieved from the load call are stored in the inputData instance and can be used as
seen in the previous trace code.

8. Save the Flash file in the same location as the


my_data.txt file and run the movie using Control ➤
Test Movie. Here’s what the output looks like on a
Mac:

Remember, because you’re using trace to display into the Output window,
opening the generated SWF on its own won’t achieve anything—you have to
use Control ➤ Test Movie.

So what have you got? Well, Flash has now fetched that data for you from an external source.

If you’re thinking, “Well, I could have just typed that in manually and saved a lot of trouble!” then you need
to get your head around the projected possibilities brought on by this admittedly basic data-loading example.

6
ONLINE GAMING WITH PHP AND MYSQL

With a little work on this file, you could create an easily updateable Flash website—easily updateable
because you just need to amend a tiny text file rather than go through all the tedious bother of opening
the FLA, remembering how you structured it, changing the text, and uploading a new SWF file.

Why not try modifying the LoadVars01.fla file slightly to display the vari-
ables stored in a file called news.txt in dynamic text boxes? Have a try and
then look at the file LoadVars02.fla for the solution.

For anyone scared by the thought of working with a database, it’s worth knowing that many websites just
use text files for updating. It keeps everything simple. However, in slightly more complex cases they use a
server-side technology (such as PHP, ASP, or Perl) to write or amend the text file.

Using PHP and MySQL


OK, we’re not going to go into text file updating here; rather, we’re going much further up the road and
looking at working with a MySQL database, and we’re going to talk to it with a little PHP. Let’s get the brief
introductions over with and then dig into some practical exercises.

PHP First Look


PHP is a free-to-use, open source server-side scripting language used for all manners of tasks, from work-
ing with files and folders on a server to updating a database. It’s pretty impossible to cover PHP from
scratch here, but we hope this section will show those of you who fear anything to do with back-end script-
ing that it really isn’t a big deal. There are many major advantages to learning PHP for present Flash users—
for example, the huge variety of PHP/Flash tutorials online, the gentle learning curve, and the fact that
much of the syntax looks similar to ActionScript.

A for loop, for instance, looks the same in the PHP and ActionScript:

Flash ActionScript

for (i=0; i<10; i++) {


// do this
}

PHP

for ($i=0; $i<10; $i++) {


// do this
}

We’ll come clean. We lied a little, didn’t we? Although the structure is the same, variables in PHP have a
slight difference: they’re prefixed with a $ character. Other than this, though, we’re on familiar ground. You
might have also noticed that a PHP comment looks the same as a Flash comment (//). PHP code lines also
end with a semicolon (;). See? It’s just like ActionScript!

Before we get too far into PHP, let’s continue the introductions with MySQL.

7
FLASH MX 2004 GAMES MOST WANTED

MySQL First Look


MySQL is also open source, meaning there’s an open development community and it’s free. In short, it’s a
powerful database used online to store and organize all manner of data.

Structured Query Language (SQL) databases allow you to run requests (called queries) on the database.
These requests are written in code form and look something like this:

INSERT INTO highscore (score, player) VALUES ('Jim', '3200');

This particular request will insert a new record into the highscore database table, with the player name
Jim and a reasonable score of 3200. Besides inserting records, select queries can also be run to get infor-
mation from the database. This query will retrieve Jim’s score from the database:

SELECT score FROM highscore WHERE player = 'Jim';

If the previous queries looked a little scarier than PHP, don’t panic just yet. Some nice folks have invented
a graphic interface to help us with all this and to save us from learning the intricacies of yet another lan-
guage. The savior is called phpMyAdmin and it’s run through a plain old browser, making it both PC and
Mac compatible.

Many online hosts who support PHP and MySQL web hosting allow you to
manage your databases online securely using phpMyAdmin.

8
ONLINE GAMING WITH PHP AND MYSQL

Because there are only so many pages in this chapter, we can’t go through all
the required installation procedures for phpMyAdmin, PHP, and MySQL;
instead, you can find some guidance on downloading and setting these up at
the friends of ED community forums: www.friendsofed.com/forums. There
are also plenty of online resources, such as the FoxServ Project
(www.foxserv.net/portal.php), an all-in-one download that will install
PHP, MySQL, and a testing server for you.

Even if you’re not sure if this is all for you, why not read on anyway? Once you
see how easy it is to use PHP and MySQL to create some hot movies, you’ll be
off to php.net in a flash!

Creating a High-Score Table


In this next exercise you’re going to flex some muscles. You’ll create a fully functional MySQL database
high-score table. Let’s look at what you need to do:

Add a new score (this will require two bits of information: the player name and the player’s score)
Show the high scores (you’ll limit the number of displayed scores to ten—nobody is interested in
the underachievers below that!)

Working with phpMyAdmin


Let’s start by creating a new database and table using your data-churning friend, phpMyAdmin.

1. First, access phpMyAdmin through your browser window: http://127.0.0.1/~username/<phpMyAdminFolder>/


index.php

9
FLASH MX 2004 GAMES MOST WANTED

2. Beneath the MySQL header in the right pane, type mostwanted into the Create new database text field.
Then click Create.

This will create a brand-new database for you to work with for this exercise and the rest of the chapter.

If you’re working online and your web host provides you with a ready-made
database, you’ll be just fine with the one already set up. In this case, select
the existing database and skip to step 4.

3. After a little while, the page will refresh and the drop-down in the left frame will show the mostwanted
database. Select it from the drop-down to load it into the left pane.

4. In the Name text field in the right frame, type highscore. Type 2 in the Fields text field.

10
ONLINE GAMING WITH PHP AND MYSQL

In MySQL, databases can consist of one or more tables. These actually store the information that you
require. The database is a container for all of the separate tables.

Even though we won’t cover it here, you can use these tables to work
together to store and retrieve different data (such as a table of user-based
data and book data for a book sales website). This is better known as a rela-
tional database system. You don’t need to know this for the exercise ahead,
but it’s nice to know all these tidbits, even just for impressing new friends.

For this exercise, one table with two fields is all you need to store. Click Go to confirm this action. The
next page might appear very sinister at first, and this is healthy! You probably already know that a table
consists of fields, but you probably weren’t aware that each field has to be defined by type, length, and
other considerations.

The reason that MySQL likes the fields typed is so that it can be as efficient or correct as possible. For
instance, MySQL needs to know if a field is a string or a numeric, and how long the field should be. The
latter is specifically in the interest of keeping a well-oiled and speedy database.

Remember the panic of Y2K? One of the major causes of this was that the
year field of databases was set to store two characters rather than the obvi-
ous four. The reason this was done was to store a little less information (two
characters per record to be precise, or 2 bytes!) and keep the database run-
ning a little leaner and speedier.

5. Type score into the first field, and select INT from the Type drop-down. Enter 10 in the Length/Values
field. Leave all the other options as they are.

6. In the second row, type player for the Field field, select VARCHAR for the Type, and add 10 again in
the Length/Values column.

You should now have the following onscreen:

11
FLASH MX 2004 GAMES MOST WANTED

So what happened here? Well, you’re creating two rows for this table, score and player, and each row
is being typed appropriately to the information it will store.

The score field was set to INT (short for “integer”), specifying it as a numeric field, whereas player was
set to VARCHAR (a variable-length string). We’re not going to go into any specifics about all the field
types available, because there are extensive pros and cons for each of them. For this simple task here,
we’re being quite generous with the field lengths, and we’re not giving much consideration to database
optimization or speed. The length of both fields as you can see is here limited to a nice round ten
characters.

For more on field types, click the Documentation hyperlink shown in


phpMyAdmin.

7. Now click Save to create the table. The page should refresh and present you with the following:

The first thing to point out is that the table is presented in the left pane, shown in the mostwanted
database (or whatever yours is called). Second, phpMyAdmin reports that the table highscore has been
created, showing that your actions were successful. Beneath this, phpMyAdmin shows you the query that
it ran for you to create the table. Remember that phpMyAdmin is simply a front-end and is creating all
the SQL queries for you (a bit like Dreamweaver producing HTML for you under the hood).

Beneath all the menu options is a visual display of the table structure with a number of available
Actions. The Change option here is most useful, as it allows you to change the structure of the table if
need be.

8. For now, though, click the Insert tab in the right pane. This will allow you to insert a record (or row)
into the database.

12
ONLINE GAMING WITH PHP AND MYSQL

9. In the Value text field of the score field, enter 3200. In the player Value field, type Jim.

10. Then click Go. Once the action is complete, the page will look like this:

13
FLASH MX 2004 GAMES MOST WANTED

For now, you don’t need to worry about the section that appears beneath
what’s pictured.

Most of this looks just like before, except that the Row Statistic area shows one row of data—this is the
record you just added! phpMyAdmin has also created the SQL query for you again (does it ring any
bells?). The query that you’ve just run is one we showed you a little earlier.

11. One other thing to note is that the


Browse option is now available. Go
on, click it. The Browse option pres-
ents you with all the records stored
in the table. At the moment, the
table is hardly bursting, but Jim can
be sure he’s the highest scoring
player—for now at least!

12. Click Insert again and add a record with 6000 as the score and your name in the player field. Then
click Go.

As before, this inserts a record into the table with the score of 6000 and your name.

13. Now click Browse again to show both records.


Big deal, huh?

14
ONLINE GAMING WITH PHP AND MYSQL

Here’s where you take a look under the hood.


OK, even though you just clicked the Browse
hyperlink and it showed you a few records, the
work for phpMyAdmin is a little more compli-
cated—it’s actually running a query for you.
Here’s how that query looks:

The SELECT command retrieves data from a table. It can require a number of parameters, but here it
simply relies on three: SELECT, FROM, and LIMIT.

SELECT *: This command requests records from the table. As most of you will be aware, the * charac-
ter is used as a wild card. Because it’s used alone here, this means all records are selected.

FROM: This command simply tells MySQL which table to get the results from. In this case, it is your
new table, highscore.

LIMIT: This command allows you to return only a select number of records. The first number repre-
sents the record number to start from, and the second one specifies the number of records to show.
This query then is providing you with a slight overkill because it’s requesting 30 records and you only
have two. Ho-hum, let’s see how to only fetch one record:

14. Click the SQL tab to bring up


the query box.

In this text field, you can type


your own queries by hand.
Scary!

15. Delete the current text in the query box and type the following exactly as shown:
SELECT * FROM 'highscore' LIMIT 0,1;

Even though single quote characters aren’t usually required for table and
row names in MySQL queries, phpMyAdmin likes to have them.

This query asks MySQL to return one record starting from the first (0). Click Go to run the query.

15
FLASH MX 2004 GAMES MOST WANTED

This time as expected, you can see only Jim’s record


because MySQL has only returned one record to you.
This might not seem that useful now, but later on it
will help you to differentiate between the top ten
players.

Before you go on to work with Flash and PHP, who


remembers the other query that we showed you ear-
lier? No one? Well, don’t bother turning back the
pages to find it because we’ll show it to you again.
Here it is:

SELECT 'score' FROM 'highscore' WHERE 'player' = 'Jim';

Given what you’ve just seen, do you want to guess


what this does? Click the SQL option and type it into
the query box to see if you’re right. For those of you
who categorize yourselves as “curious but lazy,”
here’s the answer (but you’ll have to turn the book
upside down to see it!):

OK, for now you can close phpMyAdmin and open


Flash for the next stage.

Preparing the Flash File


Before you get too excited, you’re not going to dive straight into building a game here—at the end of this
chapter you’ll put together everything that you’ve learned and look at a neat horse-racing game. Anyway,
we hope the previous chapters in the book have done enough to fuel your imagination and provide you
with tips on game creation and programming. In this section, you’re going to create a Flash interface to
communicate (via PHP, of course) with the highscore table.

Before you get down to PHP coding, you’ll create the Flash interface.

1. Create a new Flash document and rename Layer 1 buttons.


2. On the buttons layer, create two simple movie
clips using the Rectangle tool and place them in
the top corner. Give them text as shown:

3. Extend the buttons layer to frame 3 using F5.


4. Give the buttons instance names of addButton and showButton, respectively.
5. Insert a new layer called actions above the current layer and add the following code to it on frame 1:

16
ONLINE GAMING WITH PHP AND MYSQL

stop();
addButton.onRelease = function() {
_root.gotoAndStop(2);
};

6. Insert a new layer called pages between the two layers you already have and, on frame 2, click through
Insert ➤ Timeline ➤ Blank Keyframe.

7. On this keyframe, insert two text fields, and in the Property inspector, set them to Static Text. Type
PLAYER NAME: into one text field and SCORE: into the other. Arrange them vertically, roughly in the cen-
ter of the stage.

8. Alongside these, place two more text fields, with


their Properties set to Input Text. Also in the
Property inspector, give them the instance names
of playerInput and scoreInput.

9. Make sure that Show Border Around Text button


is pressed in, as you can see on the screenshot.
Also, ensure the Maximum Characters for each
input field is set to 10.

The Maximum Characters is set to ten characters to coordinate with the


maximum field values set earlier in the database. If you didn’t restrict this
and the user entered more than ten characters, only the first ten would be
recorded in the database.

10. On the same layer, create another basic button with the text
SUBMIT. Give this an instance name of submitButton.

11. Give the page a title with a static text field reading Add Score.
12. Insert a new layer called status text and place a dynamic text
field with an instance name of statusText. This should be
long and deep enough to show two lines.

This text field will be used to report any errors or successes


from the dynamic fetching and sending of data.

13. Insert a new blank keyframe on frame 2 of the actions layer


and add the following code:

17
FLASH MX 2004 GAMES MOST WANTED

stop();

submitButton.onRelease = function() {
sendData = new LoadVars();
sendData.playerOutput = _root.playerInput.text;
sendData.scoreOutput = _root.scoreInput.text;

statusText.text = "Sending Data...\nPlease wait.";

This code sets up some of the actions for the submitButton. First, as before, you set up an instance of
the LoadVars object called sendData to store the variables that are sent and received to PHP. The val-
ues inputted in the input text fields are then retrieved and set as variables within the sendData
instance.

Out of politeness (or usability, in the current parlance), the statusText box is changed, asking the user
to wait a little while.

14. Now add the following code:


sendData.onLoad = function() {
if (sendData.result == "added") {
statusText.text = "Player Score Added.";
_root.playerInput.text = "";
_root.scoreInput.text = "";
} else {
statusText.text = "Error adding score.";
}
};

As in the earlier exercise, an onLoad event handler is created for the LoadVars object. This event han-
dler is triggered when the processing with PHP is complete. The actual processes that happen in this
callback all depend on what was returned by PHP.

At this point, Flash checks if the result property of the sendData instance is equal to “added”. If it is,
a Player Score Added report is given and the input text boxes are cleared. If the result is anything
other than added, this means that something has gone amiss in the PHP code, in which case the result
is returned as something else. If you’re getting fuddled, don’t worry—this will all come into alignment
in your brain when you see the PHP code in a moment.

15. Insert this last bit of code to complete the actions for the Submit button:
sendData.sendAndLoad("insertScore.php");
};

So what happens when you call the method? First, the variables stored in the LoadVars instance are sent
out to be used by the insertScore.php file. Then PHP processes the file (with or without involvement of a
database) and returns some variables back to Flash. These variables are stored in the instance specified as
the second parameter, in this case sendData.

18
ONLINE GAMING WITH PHP AND MYSQL

You might consider having two instances of the LoadVars object, one for out-
put and one for input. This all depends on your particular project and its
complexity.

OK, now that you’re done with Flash for a moment, save the file as highscores.fla somewhere safe. You’ll
return to it in a moment.

Creating the PHP Code


Now that your Flash file is prepped, you need to create the insertScore.php file to process the variables
and create the MySQL query. Before you get started on this, though, we’d like to review the whole dynamic
process that you’re undertaking here. Luckily, it can be summed up with a simple diagram:

This diagram carefully steps through the whole process, starting with Flash sending the LoadVars data out
to the PHP document and ending with PHP returning some variables back to Flash. So far, you’ve fully pro-
grammed in both the Flash steps (the sending and receiving). Next is the PHP file.

1. Open your favorite text editor and type the following:


<?php

This declares the file as a PHP file. The browser now knows that the code to follow is to be parsed as PHP.

2. Now add the following:


$dbhost = "<enter your hostname here>";
$dbusername = "<enter your MySQL username here>";
$dbuserpassword = "<enter your MySQL password here>";
$dbname = "mostwanted";

This section of code specifies some much-needed user and database information. As we pointed out
earlier, PHP variables are prefixed with a $ symbol.

19
FLASH MX 2004 GAMES MOST WANTED

It’s worth noting that to be able to access the variables sent from Flash in
the short form demonstrated in this chapter’s PHP files, you’ll need to have
register_globals set to “On” in your php.ini file. You can access variables
in the long form through the $HTTP_POST_VARS associate array. For instance,
if the long form of your variable is $HTTP_POST_VARS['myVariable'), then
the short form of this variable is simply $myVariable.

These variables are required for connection to MySQL. Where relevant, enter your details. The user-
name and password here relate to MySQL and should not be confused with your FTP details.

Your username and password for MySQL should have been the last step
following its installation. If your site is hosted externally, you might need to
contact your host’s admin for the correct details.

Here’s an example of how these details might look:

$dbhost = "localhost";
$dbusername = "root";
$dbuserpassword = "crazyhorses";
$dbname = "mostwanted";

3. Add this code:


$link = mysql_connect ($dbhost, $dbusername, $dbuserpassword);

if (!$link) {
echo "&result=noconnection";
} else {
mysql_select_db($dbname);
}

This code connects to the database using the predefined variables. A handle, $link, is set to the
mysql_connect method, which opens up a connection to the database.

The conditional following this checks to see if the connection was successful. In the first instance, if
$link is false—that is, if the connection was unsuccessful—you use the echo command to send a vari-
able to Flash. The echo command is probably the most common PHP command that Flash scripters will
use, because it’s the most common way of sending information back to Flash.

20
ONLINE GAMING WITH PHP AND MYSQL

You can also use the echo method to write HTML, XML, and other formats to
the browser. The following code, for example, would produce a very simple
HTML page:

<?php
// A simple HTML page to say Hello!
echo "<HTML><HEAD>";
echo "<TITLE>A greeting to the people of Earth</TITLE>";
echo "</HEAD><BODY>";
echo "Hello World!";
echo "</BODY></HTML>";
?>

The usage echo "&result=noconnection"; sends a variable called result with the value of nocon-
nection to Flash. If you remember a conditional in the Flash code earlier on,

sendData.onLoad = function() {
if (sendData.result == "added") {
statusText.text = "Player Score Added.";
_root.playerInput.text = "";
_root.scoreInput.text = "";
} else {
statusText.text = "Error adding score.";
}
};

the result variable is used to check if the record was inserted successfully. The result variable, of
course, is exported from PHP and is imported into the sendData instance. If result isn’t equal to
"added", an error is reported.

4. This next bit of code is test data to check if the PHP file is working correctly. Add this to the code:
// start of temporary data //

$scoreOutput = 1500;
$playerOutput = "Eric";

// end of temporary data //

These variables mimic the exported


variables from Flash. Any variables
sent from Flash such as scoreOutput
and playerOutput are immediately
made available to PHP for use. The
only difference, of course, is that the
variables in PHP are prefixed with $.

21
FLASH MX 2004 GAMES MOST WANTED

5. Now you need to create the SQL query in PHP. Add this code:
$query = "INSERT INTO highscore (score, player) VALUES
➥('$scoreOutput', '$playerOutput');";

Because PHP and MySQL are such good pals, you can write queries in PHP and send them directly to
MySQL without much fuss. This line of code creates a string query using the variables $scoreOutput
and $playerOutput.

The actual query here isn’t really that tricky because you’ve already seen this when you entered Jim
with his mighty score of 3200 earlier in the chapter. In this case, though, you’re using variables instead
of hard values.

If some of you are a little dumbfounded by how the variables are included in the quote marks for the
string, this is because PHP can do this without breaking a sweat, simply because PHP variables are dis-
tinguished by the $ character. This means that variables can be contained within a string and are
replaced with their true value.

For example, the following variable declaration in Flash:

greeting = "Hello there " + name + "!";

looks like this in PHP:

$greeting = "Hello there $name!";

Given that name is equal to “Richard”, the greeting variable in both instances would read “Hello there
Richard!”

6. The next section of code actually calls the query:


if (mysql_query ($query)) {
echo "&result=added";
} else {
echo "&result=notadded";
}

?>

The mysql_query command runs the query passed as an argument to it, in this case the $query vari-
able. If the operation is successful, the result variable is echoed as added; if the operation was a failure,
result is exported as notadded.

Finally, the PHP code is closed using ?>.

7. Save the file as insertScore.php in a new folder called mostwanted within your web sharing or web
root folder, and then close it.

8. Once it’s saved, open it in your browser by typing in the URL.


For the file to be read correctly by the server and PHP parser, the file has to be seen through HTTP pro-
tocol. Opening the file regularly from your hard drive just won’t work! If your request was successful,
you should see something like this:

22
ONLINE GAMING WITH PHP AND MYSQL

The simple reason you’ve opened the file here is to test the temporary variables that you inserted
within the file. If you see what is shown in the previous image, this means that connection to the data-
base was successful, and the record was inserted. In the event of something other than what you see
in the previous image, you’ll need to do a little troubleshooting.

If result is equal to noconnection, then the connection to the database is unsuccessful—check that the
database and user information is correct.

If result is notadded, then chances are your query was written incorrectly. Although queries enable you
to easily talk to MySQL, they’re very strict on their structure and syntax, so you need to be careful.

If you didn’t even see result and the browser is full of garble, then you’ve typed something incorrectly
and the PHP file couldn’t be parsed because of bad syntax. In this case, check the code strictly, or copy
the file insertScore.php, which is available with this chapter’s source code.

9. If you got success in the last step, open


phpMyAdmin and select the database and table.
Click Browse to view the records.

10. You should see the new added record with Eric’s
name and frightfully low score. This proves that
the PHP file and database are talking to each
other. Keep phpMyAdmin open for now. Now
you’ll test if Flash interacts with the two.

11. Open the insertScore.php file you saved earlier


in your text editor and comment out the follow-
ing lines:

//$scoreOutput = 1500;
//$playerOutput = "Eric";

12. Locate the highscore.fla file and move it


into the mostwanted folder you created a
little while ago.

13. Open the highscore.fla file and select


File ➤ Publish. If your Publish settings are
fixed to the default position, this will pub-
lish a SWF (highscore.swf) and container
HTML page (highscore.html).

14. Open the highscore.html file from its


HTTP location. Click the Add Score button.

23
FLASH MX 2004 GAMES MOST WANTED

15. Type in a name and score, and click the SUBMIT button. After a little while, the data will be added and
the text boxes cleared:

In phpMyAdmin, a quick Browse proves that the record has been


added.

In the eventuality that Eric reappeared, you haven’t resaved the


PHP file! In any other unsuccessful eventuality, go back and check
that the Flash code is correct (or use the source files associated
with this example).

Otherwise, your high-score table is half done. So far, you can save
the scores, but you’re unable (without phpMyAdmin) to view the
scores. All that remains to do to make this fully functional is finish
the Flash file and write a new PHP file. To give you a break from
PHP, you’ll finish the Flash file first.

Creating the Leaderboard Table


The leaderboard table will display the top 10 highest scores and the corresponding player names.

Open the Flash file highscores.fla and insert


a blank keyframe on frame 3 of the pages layer.
This will house the three columns of the
leaderboard.

1. On this layer insert three dynamic text fields,


one for the position, player name, and score.

2. Give the text fields the following instance


names (from left to right): positionText,
playerText, and scoreText.

3. Give the page a title by changing the Add


Score text field to read Show Scores.

24
ONLINE GAMING WITH PHP AND MYSQL

4. Insert a blank keyframe on frame 3 of the actions layer. Attach the following code to it:
stop();
loadData = new LoadVars();
statusText.text = "Loading scoreboard.\nPlease wait.";
loadData.onLoad = function() {
if (loadData.result == "okay") {
statusText.text = "";

So far this code should all be familiar. The LoadVars instance here is called loadData, and as before, an
onLoad event is set up. In the event of a successful action, you proceed to draw the leaderboard.

5. Add this code:


for (var i = 0; i <= loadData.rows – 1; i++) {
positionText.text += i + 1 + "\n";
playerText.text += loadData["player" + i] + "\n";
scoreText.text += loadData["score" + i] + "\n";
}

The basic premise behind the table drawing is to fill each column with its own relevant data, adding a
newline character (\n) after each piece of data. The loop here is set to run according to the value of
loadData.rows, a variable accounting for the number of score records returned from PHP.

The next three lines actually write into the dynamic text fields using += to add to their current value.
Square brackets are used to allow dynamic referencing because the variables will be returned with a
suffixed figure (for example, player2, score5). More on this when you see the PHP file.

6. Now enter the following code:


} else {
statusText.text = "Error loading data.";
}
};
loadData.load("showScores.php?"+Math.round(Math.random()*1000000));

Most of this code should be familiar to you by now, so we’ll save our breath. The last thing to do in this
Flash file is add the code for the Show Scores button.

Note that the random integer query string added to the filename in the
load() call is in place to prevent the browser from caching the PHP page.
Using a random number (up to a million) ensures that each call of the PHP
script is likely to be unique and fresh. Without this appendage, the browser is
likely to cache the page and potentially show the same results as previous
calls to it.

25
FLASH MX 2004 GAMES MOST WANTED

7. Select frame 1 of the actions layer and open the Actions panel. Add the following new code (highlighted):
stop();
addButton.onRelease = function() {
_root.gotoAndStop(2);
};
showButton.onRelease = function() {
gotoAndStop(3);
};
8. Now save the file and republish it. Before you can run it, you need to create the showScores.php file.

The showScores.php File


1. Open your text editor and type this familiar code:
<?php

$dbhost = "localhost";
$dbusername = "root";
$dbuserpassword = "badger";
$dbname = "mostwanted";

$link = mysql_connect ($dbhost, $dbusername, $dbuserpassword);

if (!$link) {
echo "&result=noconnection";
} else {
mysql_select_db($dbname);
}
2. Now add this:
$query = "SELECT * FROM highscore ORDER BY score DESC LIMIT 0,
➥10;";
$result = mysql_query ($query);

As before, you create a query string, this time using SELECT to fetch records from the database. This
query is basically saying this:

“SELECT all fields FROM highscore and ORDER the results according to the score field. Display the
results in DESCending order and LIMIT the results to 10 rows, starting from record 0.”

The next line of code sets a handler ($result) for the query. The handler will be used in a moment to
extract the data. This $result isn’t to be confused with the result variable that you export later.

3. And now type this:


$count = 0;

while ($query_data = mysql_fetch_array ($result)) {


$player = $query_data ["player"];
$score = $query_data ["score"];

26
ONLINE GAMING WITH PHP AND MYSQL

First, you initiate the $count variable. You’ll see how this is used in a moment. On the next line, the
while structure is set up. The mysql_fetch_array command is used here to extract a row of data as an
array. The current row or array then is stored in $query_data. The while loop here will run as long as
there are rows to extract from $result.

The next two lines set the variables $player and $score to values extracted from the current row
array. The values are extracted using what are called associative arrays. As well as the standard numeric
array type (for example, array[1]), PHP can also use string-based associative arrays (for example,
array["name"]) for storage.

The beauty of using them here, rather than using numeric arrays, is that you can reference the field of
the record directly. For those of you unable to come to terms with this array type, you’ll be glad to
know that you can use numeric arrays instead (although you’ll have to remember your table structure),
counting the fields from the left (0) and up. The last two lines then will look like this:

$player = $query_data [1];


$score = $query_data [0];

4. Add these few lines:


echo "&player$count=$player";
echo "&score$count=$score";

$count++;
}

Good old echo is used here to send the values from $player and $count out to Flash. As mentioned
earlier, the variables are exported with a suffixed number to the variable names. Say $count is 3 and
$score is 2000, the line

echo "&score$count=$score";

would give the following to Flash:

&score3=2000

Here you increment $count for the next sweep.

5. Finish the code for this file with the following:


echo "&result=okay";
echo "&rows=$count&";

?>

This sends the result variable as normal and also the number of rows reported. The latter is used in
Flash in the eventuality that there are less than ten scores in the table.

6. Save this file in the same location as the others, and name it showScores.php.

27
FLASH MX 2004 GAMES MOST WANTED

7. Now open the showScores.php file in your browser. The variables are presented in a familiar ugly
stream:

Even though this presentation is ugly, it’s also good because it proves that the query worked. If you
carefully look at the scores from left to right, they should be in descending order from highest to low-
est. As normal, if something has gone wrong, check your PHP code. The final action for this exercise is
to check that Flash is playing ball with your PHP file.

8. Run the highscore.html file and click the show


scores button. If all went well, you should see a
brief ordered list of high scores. If not, check the
Flash file code.

All of the files for this tutorial are available in the


highscore folder of this chapter’s source code, which
is downloadable from www.friendsofed.com:

highscore.fla
highscore.swf
highscore.html
insertScore.php
showScores.php

Additionally, the SQL queries in this section are available in the sql queries folder of the source code:

highscore_table.sql
highscore_data.sql
highscore_tbl+data.sql
insert_example.sql
select_example.sql
select_limit0_1.sql

OK, now you can see that you’ve created a fully functional high-score table that will work online, out of
the box.

Using the High-Score Table in a Flash Game


The previous exercise is all very well, but it lacks one thing: a game to score from! The point of a high-score
table of course is to fuel the player into going one better than the other players (or this is at least how I see
it!). With this in mind, I’ve updated Keith Peters’ addictive water game from Chapter 4, enabling it to save
scores and reveal the elite firemen corps.
28
ONLINE GAMING WITH PHP AND MYSQL

For this I’ve used my previous FLA code as a base, stitched this onto Keith’s code, and used
showScores.php and insertScore.php just as they already are. I’ve even used the same database and table.
The file is water_final_scores.fla. I recommend you open it, and I’ll show you where exactly I made the
changes.

First, because the game only allowed the user to play one game, I had to allow the user to restart. Some of
the original code then was encapsulated into a function called start. The following code in bold is new or
added:

function start() {
_root.hs.removeMovieClip();
score = 0;
score_txt.text = score;
nextBonus = 1000;
// start spraying
start_btn.onPress = function() {
squirtInt = setInterval(squirt, 50);
};
// stop spraying
start_btn.onRelease = start_btn.onReleaseOutside = function() {
clearInterval(squirtInt);
};
status_txt.text = "";
waterTank_mc.gauge_mc.waterLevel_mc._yscale = 100;
flame_mc.reset();
};

The start function is then called at the very end of the code. Next, I had to add some code to run upon
game over:

function squirt() {
// make a drop of water
var drop_mc = attachMovie("drop", "d"+depth, depth++);
// vary its size
drop_mc._xscale = drop_mc._yscale=125+Math.sin(dropSize += .9)*50;
// position it at end of nozzle
drop_mc._x = nozzle_mc._x+5;
drop_mc._y = nozzle_mc._y;
// give it some speed
drop_mc.vx = 10;
drop_mc.vy = Math.random()-.5;
// assign enterFrame handler
drop_mc.onEnterFrame = move;
// reduce water level
waterLevel -= .1;
// adjust gauge
waterTank_mc.gauge_mc.waterLevel_mc._yscale = waterLevel;
// check if water is gone

29
FLASH MX 2004 GAMES MOST WANTED

if (waterLevel<=0) {
// disable button
delete start_btn.onPress;
// stop spraying
clearInterval(squirtInt);
status_txt.text = "Game Over!";
onGameOver();
}
}

The next function is entirely new:

// when game ends this function is called


function onGameOver() {
hs = _root.attachMovie("highscoreTbl", "highscoreTbl",
➥1000005);
hs.gotoAndStop(1);
hs.submitButton.onRelease = function() {
sendData = new LoadVars();
sendData.playerOutput = hs.playerInput.text;
sendData.scoreOutput = score;

hs.statusText.text = "Sending Score to Server...\nPlease wait.";

sendData.onLoad = function() {
if (sendData.result == "added") {
hs.statusText.text = "Player Score Added.";
hs.playerInput.text = "";
hs.scoreInput.text = "";
} else {
statusText.text = "Error adding score.";
}
status_txt.text = "";
getHighScores();
};

sendData.sendAndLoad("insertScore.php", sendData, "POST");


};
}

Let’s look at what’s happening here. First, a newly added movie clip called highscore page (located in the
high score assets folder) is attached from the Library. This movie clip contains two frames (as in previous
example): one for adding a player’s score and the other for displaying the high scores. Take a look.

This is then sent to frame 1, the adding page. The player (regardless of her score) is invited to add her
name as before. This time her score is set as the score variable from the game. This prevents the user from
cheating and entering her own score.

30
ONLINE GAMING WITH PHP AND MYSQL

The rest of the code here mimics the previous FLA, with the exception of the getHighScores function call
at the end of the onLoad handler. That function is coming right up.

// retrieve high scores


function getHighScores() {
hs.gotoAndStop (2);
loadData = new LoadVars();
hs.statusText.text = "Loading scoreboard.\nPlease wait.";
loadData.onLoad = function() {
if (loadData.result == "okay") {
status_txt.text = "The Top 10 Extinguishers";
hs.statusText.text = "";
//
hs.scoresTxt.text = "";
for (var i = 0; i <= loadData.rows – 1; i++) {
hs.scoresTxt.text += loadData["player" + i] + " ";
hs.scoresTxt.text += loadData["score" + i] + "\n";
}
} else {
hs.statusText.text = "Error loading data.";
}
hs.replayButton.onRelease = function() {
start();
};
};
loadData.sendAndLoad("showScores.php", loadData, "POST");
}

Unlike in the previous FLA, in which you requested the high-score table, this time it’s automatically shown
after the player enters his name. The only difference here is how the table is displayed, using a single cen-
tered dynamic text field (scoresTxt):

31
FLASH MX 2004 GAMES MOST WANTED

The Play Again button then launches the start function to reset the score, remove the score page
(_root.hs.removeMovieClip();), and start the flame afresh.

As you can see here, there isn’t much that I’ve changed in the original game file—much of the code is just
tweaking to make the game run from the start again. The actual saving and retrieving code is only a little
different, and better still, I’ve made no changes to the database or PHP files!

When you come to run this version of the game, remember that you’ll need to launch it in a browser from
a web server URL. The game’s HTML and SWF files should also be in the same folder as the PHP files for it
all to work.

You can find all the files for this tutorial with this chapter’s example downloads, in the water folder:

water_score_final.html
water_score_final.swf
water_score_final.fla
insertScore.php
showScores.php

This high-score table is pretty successful and quite fast. However, the one disadvantage of it is that every
score is entered into the database. If you imagine some hard-core gamer whiling away most of his hours
(when he should be working) playing this, the database can quickly become overcrowded.

The simple way around this is to check the score is worthy of a placement in the leaderboard before
adding it. If the score is high enough for, say, the top 100, add it to the database; if it’s lower than the top
100, reject it. The best way to do this would be to check the score against the database scores at the end
of the game. We’re not going to cover that here, but with a little research it should be within your grasp
very soon.

32
ONLINE GAMING WITH PHP AND MYSQL

Lollipop Break
If you’ve made it this far, reward yourself with a lollipop—you’ve done very well. We didn’t say it would be
easy, and it might not have been as fun as some of the earlier chapters, but the important thing is that
you’ve made the leap from Flash designer to Flash developer in a small number of pages.

As we pointed out before you started, the purpose of this chapter isn’t to teach you PHP and MySQL from
scratch, but to try to get you working with them and also to provide you with a fully functioning high-score
table. For those of you keen to look into using PHP and MySQL with Flash a little more, we recommend a
couple of books from friends of ED: Foundation PHP for Flash and Advanced PHP for Flash will give you a
superb grounding in these technologies. These books, coupled with knowledge of the LoadVars object, will
help you hit the ground running. And it’s worth staying tuned to www.friendsofed.com to hear about new
PHP books.

Dynamic Gaming Case Study: The Race-A-Lot Game


Time for a case study. Before you depart, you’ll
take a quick look at my Race-A-Lot game. This
super lo-fi creation is a simple horse-gambling
game based on a fairground amusement arcade
machine.

Like its arcade equivalent, this game is simple to


the extreme. But it can still draw the punters in!
Its key difference is the persistence of player
data. Each player first registers on the site, is
given (a virtual) £200, and can gamble. Players
can then continue their gambling addiction by
logging on at any time using their registered user-
name and password.

As you can probably guess, PHP and MySQL


are used to do all the magic behind the stor-
age of information. Besides the standard
updates, a couple of other options are avail-
able that use both technologies:

Personal lifetime gambling statistics

A list of the top gamblers

In this section, we’ll detail some of the hap-


penings and show you the PHP code for the
different events. Before that, though, let’s
talk a little about the actual game.

33
FLASH MX 2004 GAMES MOST WANTED

Race for the Prize


As previously mentioned, the inspiration for this game is a seaside amusement machine. Not only is the
game a favorite of mine to waste pennies on, but it also has the best sound design (I suppose you can call
it that . . .) from a computer/human sample of “Place Your Bets Now, Please!” to the sound of the gates
going up and the horses trotting.

First, let me point out that the arcade is a little clunky. It’s a huge triangular glass cabinet with plastic hybrid
horse/jockeys models of many bright colors. To re-create the effect in Flash would need a little attention,
but I think the most important aspect to get right is its quirky motion.

The movement of the horses in the cabinet is stunted, jolty, and irregular. To mimic this, I used a very sim-
ilar method, giving each horse the same standard round speed (a round is specified as an interval that
recurs every second) and the random chance of a bonus boost. The total round speed then (from the stan-
dard speed + the bonus distance) is given to the horse to run over a second, producing a very staggered
and nigh-on impossible burst. I did originally try the horses with inertia-based movement, but this was far
too clean for this particular game.

Another idea stolen from the arcade game is the continual racing of the horses. To attract attention, the
horses continually race, allowing only a brief moment to bet on them. To give a similar live feel to it, I went
with the same method, allowing the horses to race without waiting for the player’s permission to race.
Watching other people playing this, I’ve noticed that they tend to impulse bet and are constantly aware of
the clock counting down.

The live game is viewable at www.graphci.com/horse, so you can see how the dynamic files work in prac-
tice. All the required files are available with this chapter’s source code, within the horse folder.

34
ONLINE GAMING WITH PHP AND MYSQL

In the next few sections, I’ll detail the purpose of every one of the PHP files. This knowledge, coupled with
the FLA, should allow you to make something similar in a snap!

Dissecting the Game


A little like the high-scores FLA, the file is split over three keyframes. The first keyframe has a login screen,
and the second has a registration screen. The actual game playing takes place on frame 3.

Before you look at the individual files, let’s look at the table structure to see what information is stored for
each player:

Here’s what data the records store:

username: The player’s username data. No two usernames can be the same, so a check is provided to
ensure that a username isn’t already taken (addUser.php).

password: The individual’s password. This is used for logging on.

winnings: The amount of cash in the player’s pocket. This cash is used to bet and for the leaderboard.

bankrupts: The number of times the player has been made bankrupt. This is used to shame the player
on the My Stats screen.

raceswon: The number of bets the player has won.

racesrun: The number of races the player has bet on.

registerdate: The date the user registered as a player. This data is stored as a UNIX timestamp, a date
taken from the server. I’ve limited this to eight characters, so that it reports the date in the following
format: yyyymmdd. Timestamps can report the time as well as date.

A typical player’s details then will look like this:

With these details in mind, let’s look at some of


the dynamic functionality that takes place at
different times in the game.

35
FLASH MX 2004 GAMES MOST WANTED

First Time at the Track, Sir?


The registration screen is typical and consists of three text
fields: username, password, and a confirmation box for the
password.

As with any login forms, a number of checks are provided to


ensure that the user details are correct. Most of these (check-
ing the password and confirming password text are identical)
are actually processed in Flash. The only check that is done
dynamically is to see if the username entered already exists.
The submit button actually sends the entered details to the
addUser.php file:

<?php

// addUser.php //
// adds a user's details to the database //

include "connect_db.inc.php";

$query = "SELECT username FROM horses WHERE username = '$userInput'";


$returned = mysql_query ($query);

$rownums = mysql_num_rows ($returned);

if ($rownums > 0) {
echo "&result=userexists";

} else {

$query = "INSERT INTO horses (username, password, winnings,


➥registerdate) VALUES ('$userInput','$passInput', 200, NOW());";

if (mysql_query ($query)) {
echo "&result=added";
} else {
echo "&result=notadded";
}
}

?>

The first bold line here attempts to fetch a record from the database with the username that was entered
in the Flash movie ($userInput). The intention here is to check if the username already exists in the data-
base. The variable $rownums is set to the number of rows of data fetched from the query (using the
mysql_num_rows command).

The final bold line then checks to see if any rows were returned. In the event that none were returned (the
username doesn’t already exist), the user is added to the database.

36
ONLINE GAMING WITH PHP AND MYSQL

The NOW() function here adds the current date to the registerdate field. This fetches the current date
from the UNIX server as opposed to the user’s own machine.

Down to the Nags


Logging in the player is a rather simple affair that calls the loginUser.php file. This time the required checks
are processed within the PHP file.

<?php

// loginUser.php //
// login a user //

include "connect_db.inc.php";

$query = "SELECT username, password, winnings FROM horses WHERE


➥username = '$userInput'";
$result = mysql_query ($query);

$rownums = mysql_num_rows ($result);

if ($rownums > 0) {
$query_data = mysql_fetch_array ($result);

if ($passInput == $query_data["password"]) {
echo "&result=loggedin";
//
$storedMoney = $query_data["winnings"];
echo "&money=$storedMoney";
} else {
echo "&result=wrongpassword";
}
} else {
echo "&result=nouser";
}

?>

This time the query requests the username, password, and winnings from the database. As before
$rownums is used to check if the user exists in the database. If the user doesn’t exist in the database, the
result variable is returned as nouser and Flash returns a suitable error.

If the user exists, the next check required sees if the user has the right password. $passInput, which rep-
resents the inputted password from the Flash text field, is checked against the stored database password
information. If the password is correct, the stored cash is sent to Flash; if the password isn’t correct, result
is returned as wrongpassword. Flash will then report appropriately according to either eventuality.

The default else here refers to the user not existing. Flash is then informed of this. If the user is logged in,
the user is sent to frame 3 to play the game.

37
FLASH MX 2004 GAMES MOST WANTED

Putting the Check in the Bank


When it came to updating the users’ data, I faced a choice. On one hand, I could simply save on logout, or
I could save at certain points of the game. The problem with the former choice, of course, is the possibility
of cheating, allowing the player to close the game on bankruptcy. This was simply wrong!

I opted then to save the general data after every five races or, of course, on logout. The thisrace variable
in Flash is incremented every race, and when it hits 5, the updateAll.php file is called from Flash. However,
when this is called, the game continues (so the user is unaware and the experience is seamless).

<?php

// updateAll.php //
// update a number of fields in the database //

include "connect_db.inc.php";

// update winnings //

$winquery = "UPDATE horses SET winnings = $cash WHERE username =


➥'$userdata';";
$winreturned = mysql_query ($winquery);

// update races run by 1 //

if ($racenum > 0) {
$racequery = "UPDATE horses SET racesrun = racesrun + $racenum
➥WHERE username = '$userdata';";
$runreturned = mysql_query ($racequery);
}

// update won races by 1 //

if ($wonraces > 0) {
$wonquery = "UPDATE horses SET raceswon = raceswon + $wonraces
➥WHERE username = '$userdata';";
$wonreturned = mysql_query ($wonquery);
}

?>

You might notice here that the queries look a little different from any you’ve seen before. The UPDATE
command is pretty self-explanatory: it simply allows you to update the values stored in a particular field of
a record. Remember that INSERT is used to write a new record. UPDATE therefore is essential for any main-
tenance on the records.

An Appointment with the Bank Manager


In most games, running out of lives or cash usually fills the screen with a dreaded GAME OVER screen, but
not here! Like big old softies, we don’t allow that to happen. When you run out of cash in this game, you’re
allowed to continue and you’re handed a wedge of freshly printed notes.

38
ONLINE GAMING WITH PHP AND MYSQL

However, the bank manager (who kindly gives you the


money) makes a note of it. The file incrementBankrupt.php
is used to increment it in the database.

<?php

// incrementBankrupt.php //
// add one to bankrupts value /

include "connect_db.inc.php";

$query = "UPDATE horses SET bankrupts =


➥bankrupts + 1 WHERE username =
➥'$userdata';";
$result = mysql_query ($query);

if (!$result) {
echo "&result=error";
}

?>

As with the updateAll.php file, the UPDATE command is called, and the value stored in the bankrupts row is
incremented by 1. The value of the bankrupts row is displayed when the user requests her personal statistics.

Racing Form
One of the benefits of storing the user’s data is the ability to recall the
user’s total records at any time. In this game, certain data is kept to
allow a user to review her betting abilities. The values stored in the
raceswon and racesrun rows, for example, are used to calculate a
win/bet ratio.

The bankrupts row is used to shame the player and to calculate the
player’s total money after bank loans. All of the code here is quite
straightforward:

<?php

// getMyStats.php //
// get user's stats //

include "connect_db.inc.php";

$query = "SELECT * FROM horses WHERE username =


'$userdata';";
$result = mysql_query ($query);

$query_data = mysql_fetch_array ($result);

39
FLASH MX 2004 GAMES MOST WANTED

$player = $query_data ["username"];


$cash = $query_data ["winnings"];
$wins = $query_data ["raceswon"];
$races = $query_data ["racesrun"];
$bankrupts = $query_data ["bankrupts"];
$startDate = $query_data ["registerdate"];

echo "&player=$player";
echo "&cash=$cash";
echo "&wins=$wins";
echo "&races=$races";
echo "&startDate=$startDate";
echo "&bankrupts=$bankrupts";

echo "&result=okay";

?>

Who’s Your Daddy?


As with any other game, competition is the key. The high-score
board is ordered by the amount of cash in the players’ pockets,
but it also displays the players’ win/bet ratio. This allows you to
see if a player just earned all their cash from one race in a total
fluke, or if a player is a consistent earner.

The leaderboard is activated by a button in the bottom-right cor-


ner and calls the data from the showLeaderboard.php file:

<?php

// showLeaderboard.php //
// report top 20 players according to score //

include "connect_db.inc.php";

$query = "SELECT * FROM horses ORDER BY winnings DESC LIMIT 0,


➥20;";
$result = mysql_query ($query);

$count = 0;

echo "&result=okay";

while ($query_data = mysql_fetch_array ($result)) {

$player = $query_data ["username"];


$cash = $query_data ["winnings"];
$wins = $query_data ["raceswon"];
$races = $query_data ["racesrun"];

40
ONLINE GAMING WITH PHP AND MYSQL

if ($wins > 0 && $races > 0) {


$winratio = ($wins / $races) * 100;
$winratio = number_format($winratio, 1);
echo "&player$count=$player";
echo "&cash$count=$cash";
echo "&winratio$count=$winratio";

$count++;
}
}

echo "&rows=$count";

?>

Other PHP Files


The only other files required by the game are common_db.inc.php (to store MySQL database login infor-
mation):

<?php

// common_db.inc.php //
// stores mysql dbase login info //

$dbhost = "<localhost or mysql server>";


$dbusername = "<username>";
$dbuserpassword = "<password>";
$dbname = "mostwanted";

?>

and connect_db.inc.php (to connect to the database):

<?php

// connect_db.inc.php //
// login to database //

include "common_db.inc.php";

$link = mysql_connect ($dbhost, $dbusername, $dbuserpassword);

if (!$link) {
echo "&result=noconnection";
} else {
mysql_select_db($dbname);
}

?>

41
FLASH MX 2004 GAMES MOST WANTED

Summary
It wasn’t possible to go into depth about every aspect of the game here, but I’ve tried to outline some of
the situations and processes involved so you know how to approach a similar project.

From a game point of view, there are many things here that I would like to have done differently given a
little more time. The original game, for instance, was intended to be isometric, with the movement consid-
erations put in place (this might get considered in future, of course). The odds of the horses were also
meant to change according to form and many other variables. I also wanted to make a random horse name
generator.

If you have any suggestions or comments on the game, I’d love to hear them. E-mail them to
horses@graphci.com, and have fun with these files!

42

Você também pode gostar