Storing Flash Variables into MySQL

Flash Meets MySQL

When I first needed a simple function to store a few Flash variables into a MySQL database (through PHP), I actually had to search more than I wanted to. So in order to save myself some future trouble (and time), I created a very simple AS3 class capable of receiving variables and passing them to a server-side PHP.

So here’s the class. Copy the code and save this file as Server.as in the root folder of your project.

package {
	import flash.events.*;
	import flash.net.*;
 
public class Server {
 
public function sendVars(getVar1:Number, getVar2:Number):void {
 
var variables:URLVariables = new URLVariables();
var myRequest:URLRequest = new URLRequest("http://localhost/save.php");
myRequest.method = URLRequestMethod.POST;
 
variables.myPoints = String(getVar1);
variables.myTime = String(getVar2);
myRequest.data = variables;
 
var loader:URLLoader = new URLLoader();
loader.load(myRequest);
loader.addEventListener(Event.COMPLETE, sendData);
 
    function sendData(evt:Event):void{
      trace(evt.target.data);
    }
}
}
}

Some explanation is in order. getVar1 and getVar2 found between the function parameters are the two variables we’re gonna send, and we’re getting these from the main FLA. We’re also assuming they will be Numbers. Don’t forget to define these as variables to send through our PHP, in which we define their names: in this case, one is called myTime and the other one myPoints. You can change these as long as you change the PHP as well.

Next, this is how you will call this function within your main FLA file:

First, we create and define the new Server class.

var sendScore:Server=new Server();

Next, we call the function whenever needed, passing the number of variables the main function is willing to accept. In this case, two:

sendScore.sendVars(times, score);

Now, the PHP file. I am assuming you already have your MySQL database created. The PHP code:

<?php
$con = mysql_connect("localhost","admin","password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
 
mysql_select_db("mydatabase", $con);
extract($_REQUEST);
mysql_query("INSERT INTO tb_table (score, times) VALUES ('$myPoints', '$myTime')");
mysql_close($con);
?>

This is where the magic happens.
Connect to your database, extract the request, and insert the variables created within the Server class into some table.
The beauty of this method is that you’re also able to send variables from the MySQL to the Flash. Simply echo them in this file and get them in Flash, in the sendData() function.

All done!