This article explains in the most simpliest terms how to use action script to connect to MySQL via a php file in order to extract data for display in your flash application.
First, you build a flash game that keeps track and stores the gamer’s score. Before we even discuss that (in another article: http://www.jamesandchey.net/?p=530),
we want to retrieve the top score from the database saved from a previous game and display it to the current gamer.
To retreive the top score, you need to add code to your action script to call a php file on your server.
First, define a URLLoader variable.
Next, define a URLRequest variable that contains the url location of your php file. Also, assign the GET method to your URLRequest variable.
You then need to define an event listener to your URLLoader so it can fire a function (that your define) once the data is returned to your flash application via the php file.
The function you define will take the data (built in XML format by the php file) and load it into textbox variables for display.
Lastly, execute the load method of the URLLoader passing as a parameter the URLRequest variable.
Below is the code:
var varLoaderGet:URLLoader = new URLLoader;
var varGet:URLRequest = new URLRequest("http://www.somewebsite.com/flash/somefile_GET.php");
varGet.method = URLRequestMethod.GET;
varLoaderGet.addEventListener(Event.COMPLETE, loaderGetCompleteHandler, false, 0, true);
varLoaderGet.load(varGet);
function loaderGetCompleteHandler(e:Event):void
{
var dataXML:XML = XML(e.target.data);
_SQLDatePlayed.text = (dataXML.item[0]);
_SQLName.text = (dataXML.item[1]);
_SQLLevel.text = (dataXML.item[2]);
_SQLScore.text = (dataXML.item[3]);
}
Now that the action script code is explained, let’s talk about the php file that gets called by your flash application.
The first part of your php file connects to MySQL and establishes the database name.
Next, you build your query statement to retrieve the data.
Lastly, you execute the query and store the results in your result string.
Now that you have the data, you build the xml file using the echo statement.
The php finishes off by closing your database connection.
Below is the code:
somefile_GET.php
<?PHP
$link = mysql_connect("localhost", "userid", "password");
mysql_select_db("flash_database");
$query = 'SELECT * FROM flash_game_table order by score desc, date_played desc LIMIT 1';
$results = mysql_query($query);
echo "n";
echo "n";
while($line = mysql_fetch_assoc($results)) {
echo "- " . $line["date_played"] . "
n";
echo "- " . $line["name"] . "
n";
echo "- " . $line["level"] . "
n";
echo "- " . $line["score"] . "
n";
}
echo " n";
mysql_close($link);
?>