This article explains in the most simpliest terms how to use action script to connect to MySQL via a php file in order to post data from your flash application.
First, you build a flash game that keeps track of the gamer’s score. At the end of the game, you want to save the gamer’s score to your database.
To save the score, you need to add code to your action script to call a php file on your server.
First, define a URLVariables variable. Appended to this variable are the game statistics that you want to pass to your php file. (PlayerName, PlayerScore)
Second, you define a URLLoader variable.
Next, define a URLRequest variable that contains the url location of your php file. You then assign the POST method to your URLRequest variable and assign your defined variables to it’s data method.
Lastly, you assign the TEXT data format to your URLLoader, then execute the load method of the URLLoader passing as a parameter the URLRequest variable.
Below is the code:
var variables:URLVariables = new URLVariables; variables.PlayerName = txtPlayerName.text; variables.PlayerScore = txtPlayerScore.text; var varLoaderPost:URLLoader = new URLLoader; var varSend:URLRequest = new URLRequest("http://www.somewebsite.com/flash/somefile_POST.php"); varSend.method = URLRequestMethod.POST; varSend.data = variables; varLoaderPost.dataFormat = URLLoaderDataFormat.TEXT; varLoaderPost.load(varSend);
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.
Second, you receive the player name and player score posted to the php and assign them to php variables.
Third, you get the current date. (The time zone is set at the beginning of the php file to whatever time zone you prefer)
Next, you build the insert sql statement.
Lastly, you execute the sql statement. The player’s data is now stored in the database.
The php finishes off by closing your database connection.
Below is the code:
<?PHP date_default_timezone_set('EST'); $link = mysql_connect("localhost", "username", "password"); mysql_select_db("flash_database") or die ("no database"); $PlayerName = $_POST['PlayerName']; $PlayerScore = $_POST['PlayerScore']; // Get the current date $current_date = date('Y-m-d H:i:s'); $sqlCommand = "INSERT INTO flash_game_table (date_played, name, score) VALUES('$current_date ', '$PlayerName', '$PlayerScore')"; $results = mysql_query($sqlCommand) or die (mysql_error()); mysql_close($link); ?>