www.SonSoftCo.com

Easy steps to make AS3 (ActionScript 3) interact with PHP, and finally MySQL


Download Source Files

The following code goes into your Flash Timeline:

  var str:String = "";
var myscore = 0;
btn_submit.addEventListener(MouseEvent.CLICK, submitted);

function submitted(e:MouseEvent)
{
var myrequest:URLRequest = new URLRequest("http://www.sonsoftco.com/AS3-PHP-MYSQL.php");
myrequest.method = URLRequestMethod.POST;
var variables:URLVariables = new URLVariables();
variables.name = str;
variables.score = myscore;
myrequest.data = variables;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, dataOnLoad);
loader.load(myrequest);
}

function dataOnLoad(evt:Event)
{
MC_success.alpha=100;
//status is a custom flag passed from back-end
}
I'm going to assume that you have some AS3 knowledge and explain only the significant lines for connecting with the PHP script.
The first step is declaring our variables to use (str & myscore), add an event listener to our submit button, and start our function.
URLRequest is going to be the location of our PHP file that we are going to be sending our information.
The next line tells Flash which method to send the information with, either GET or POST. GET is the default, POST can send larger amounts of information though.
var variables:URLVariables = new URLVariables(); Sets up the Object that will be sent to the PHP file. Think of it like a package delivery containing whatever we want to send.
The name & score are the values that are going to be sent in our "variables" package. These are useful for a High Scores link for a game.
You could change these to anything you need. (ex: first & last names, email addresses, and phone #'s for a customer database)
URLLoader is the actual class that sends the AS3 information to the PHP script.
We add a listener for the "OK" from the server, load(myrequest) sends our information.
Once the "OK" comes back, we run a function called dataOnLoad which could run any sort of code you want. gotoAndPlay() would be a great way to advance through your Timeline.
I happen to have a MovieClip named MC_success dragged into the frame with an alpha of 0%, so when the data is sent successfully, it shows up to let us know.

Creating a PHP file to accept data from Flash AS3:
  var str:String = "";
//Include database connection details
require_once('config.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}

//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}

//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}

//Sanitize the POST values
$name = clean($_POST['username']);
$score = clean($_POST['score']);
$currentdate = date("Y/m/d");

//Create INSERT query
$qry = "INSERT INTO highscores(user,time,date) VALUES('$name','$score','$currentdate')";
$result = @mysql_query($qry);
echo "writing=Ok";
exit();
mysql_close();
?>
Paste the above script into a text file and save it as AS3-PHP-MYSQL.php (which we named in our Flash project).
Notes in the script explain pretty much all of it. *IMPORTANT* You need to create a config.php file also and have your database login details set up.
This script connects to the database, then cleans our information from Flash to make sure someone isn't trying to hack or crash your server/database.
Then we declare PHP variables with $name and $score lines. The date I have in there just to keep track of when people submit their scores.
We interact with MySQL storing our query in $qry, then using it with the @mysql_query command.
The '@' sign is not necessary but it adds security when sending information.
echo "writing=Ok"; returns the OK to AS3 so that the movie can continue to your next function.
It's good practice to mysql_close(); your connection to the database to help the server &/or your hosting company.

Create your MySQL database:
Pretty simple here, login to your phpMyAdmin account or whatever you use to manage MySQL.
You will need to create a database, use any name you want.
Create a table called 'highscores' with fields named 'user', 'time', & 'date' as you can see in the PHP script.

Forgot to mention, you will need to create another PHP file that will display the database.
It is included in the AS3-PHP-MYSQL zip file. Very easy to understand, its quite similar to the above PHP file.
And That's all there is to it! Happy Hacking!
Download Source Files