Tutorial: High Score Table with Flash and PHP

In this tutorial we'll take a look at how to build your own high score system using Flash ActionScript 3.0 on the client side and PHP on the server side to handle database tasks. This is meant only as a starting point as we do not do much, if any, error checking or security checks on the data submitted to the database. I am not well-versed in PHP so if you are and notice some mistakes, feel free to point them out!

For this tutorial, I'm using the standard XAMPP server on my local machine. If you want to follow along, go ahead and download XAMPP and install it. Once installed, use the control panel and make sure that at least the Apache and MySQL services are running. If you open a web browser and browse to localhost or 127.0.0.1 and see something like this, then you're good to go.

Click on the phpMyAdmin link in the lefthand column and it should take you to the database management area. From here, there should already be a database named test as shown below.

Click on test. Now we want to create a table. This table will hold our high scores so just enter a name for the table; I used scores. This table will have just 2 columns: a user and a score. Click the Go button as indicated in the image below.

This next page is where we add the actual data fields to the table. Remember, we wanted two fields: User and Score. Fill in the boxes as shown below and click the Save button to create these fields.

Congratulations, you have just added the high score table to the database! Great! But now what? Well, next up we'll get into a little PHP code so that we can connect to our database and talk to it. Don't worry if you aren't too familiar with PHP, there isn't a whole lot we need to do. Open up any ol' text editor you like. Heck, notepad will suffice for this, but I'm using notepad++.

Create a new file and save it to the xampp htdocs directory. This path is C:\xampp\htdocs by default. Save the file with the name connect.php and get ready to go into beast mode for some PHP programming! Ok, its more like baby mode, but that doesn't sound as exciting does it? Below is the code for connect.php.

<?php

$user = 'root';
$pass = '';
$dbName = 'test';

$mysqli = new mysqli('127.0.0.1', $user, $pass, $dbName);

if($mysqli->connect_errno)
{
	echo "Failed to connect: " . $mysqli->connect_error;
}

?>

Alright, let's go over this code to make sure we understand what's happening. If you aren't familiar with PHP, all variables start with the dollar sign ($). So first we declare and assign three variables. When connecting to a database, you need to provide a username and password. For phpMyAdmin the default username is root and the default password is blank. The third variable is the name of the database we want to connect to. Next we connect to the database using a call to new mysqli (which is the modern php mysql interface, the i stands for improved). You can read up on it here if you'd like. Lastly, we just check for an error. Assuming everything is set up properly, we shouldn't have any.

That wasn't so bad, was it? I hope not because we've got two more short php files to write. We'll have one for submitting a score to the database and another for reading scores out of it. We'll begin with the reading first. Create a new php file in the same directory as the connect.php file. Name it getScores.php and enter the following code.

<?php

include('connect.php');

$query = 'SELECT * FROM scores ORDER BY Score DESC LIMIT 5';

$result = $mysqli->query($query);

$returnString = '';

while($row = $result->fetch_assoc())
{
	$returnString .= ($row['User'] . ' ' . $row['Score'] . '#');
}

echo $returnString;

?>

What's going on here? Well first we include our connect.php script. This connects us to the database and gives us access to the $mysqli variable declared there. Next we set up a basic query string saying that we want the top 5 scores from the scores table and we want them in descending order (so the top score is first in the list). After that we actually execute that query and store the results in our $result variable. Once we've got our results, I'm setting up a variable which will just be a string containing the results. Then we do a while loop and fetch the data from the $result variable and concatenate it onto our $returnString variable. Notice I'm also appending a hashtag at the end. This is not required, but I like to get the data as a string and I do this to make things simpler on the Flash side for myself.

Finally when the loop is done, we just echo the $returnString variable. When we echo this variable, it gets sent back to Flash as a response from the server.

Now we can connect to the database and also read from it! This is all well and good, but not especially useful without a way to actually put data into it. Let's do that now. Create yet another PHP file in the same directory as before and name this one submitScore.php. Here is the code for this one.

<?php

include('connect.php');

$user		= $_POST['user'];
$score 		= $_POST['score'];
$query		= "INSERT INTO scores (User, Score) VALUES ('" . $user . "', '" . $score . "')";

$mysqli->query($query);

$query 			= "SELECT * FROM scores WHERE Score >= " . $score;
$result			= $mysqli->query($query);
$returnValue 	= $result->num_rows;

$result->close();

echo $returnValue;

?>

Once again you can see we begin by including the connect.php file. After that we extract the data that gets sent from Flash and store it in two variables: $user and $score. We send the data from Flash in a POST request (as opposed to GET) and that's why we use the special $_POST variable to get our data. Next we set up a query, but unlike the query in the getScores file, this one is inserting values into the database. After building the query string, we execute the query. At this point, our data should be safely stored in the database.

You could stop here if you wanted to, but we're doing a little extra and getting the placement of the user's score from the database. For that, we build another query. This is another SELECT query which will read from the database. We execute the query and store the results. Then we find out how many rows were returned in the result set and store that value in our $returnValue variable. After that we free up our results by calling the close method and finally echo $returnValue. This will tell us where the user ranks among all entries in the database. Though it isn't entirely accurate since we only searched by score, it will suffice for this tutorial.

Next up, we'll handle the Flash side.

Pages: 1 2

Bookmark and Share

4 Responses to “Tutorial: High Score Table with Flash and PHP”

  1. Jaspher says:

    After searching so many BULLSHITs on the google.. AT LAST! i see this tutorial
    it helps me a LOT sir, thank you so much for this! :D

  2. Jimber says:

    it is working in action script 2.0? :(

  3. Eugene says:

    thank sir.. it will help me in my game…

  4. Rhuno says:

    No, this is not AS 2.

Leave a Reply

Subscribe to RSS feed FGS5 Badge