Creating High Score / Top Scores / Data Table in Adobe Flash CS3
15 Oct 2007 Quan Quach 55 comments 11,385 views
Part 2: Writing data to MySQL using Flash/PHP
In order to keep a record of all the top scores, we need a way to write data to the database! Now that we have confirmed that the database was imported correctly, we can move on to writing data to the MySQL database. In the Flash game I developed, the user inserts a name after completing the three rounds. Once this happens, the game sends the user data to a PHP script which in turns writes the data to the MySQL table. Let’s look at the code that will accomplish this.
- Open up a new Flash File (Actionscript 3.0). Press F9 and paste in the following code into the Actions - Frame. This code uses what is known as URL variables to send data to the PHP script. If you don’t know what URL variables are, you might want to check out this quick tutorial here. One of the lines must be modified with the address of the accompanying php file. The accompanying php file is shown in the next step.
import fl.controls.TextInput; import fl.controls.TextArea; var variables:URLVariables = new URLVariables(); variables.name = "Zzyzx"; variables.roundOne = 1.341; variables.roundTwo = 2.111; variables.roundThree = 2.222; variables.final = 1.341+2.111+2.222; var request:URLRequest = new URLRequest(); ////insert in the location of the php script //////////////// request.url = "insert the web address of php file here"; ////////////////////////////////////////////////////////////// request.data = variables; var loader:URLLoader = new URLLoader(); loader.load(request); //sends the request //when the request is done loading, it goes to the completeWriting function loader.addEventListener(Event.COMPLETE, completeWriting); function completeWriting(event:Event):void { var writingCompleted:TextField = new TextField; writingCompleted.autoSize = "center"; writingCompleted.x =200; writingCompleted.y= 200; writingCompleted.text = event.target.data; addChild(writingCompleted); }
- Now that we have the code to send the data within flash to the PHP script, it might be useful to write the actual PHP script! The following script takes in URL variables from flash, and then writes the pertinent information to the MySQL database. Copy and paste this code, and save it as a php file. Remember to fill in the information for the host, username, password, etc.
<?php ////////////////// modify this information /////////////////////// $host = "localhost"; $user = ""; $pass= ""; $table = ""; $database = ""; /////////////////////////////////////////////////////////////////////// //stores the URLvariables into variables that php can use $one = $_GET['name']; $two = $_GET['roundOne']; $three= $_GET['roundTwo']; $four = $_GET['roundThree']; $five = $_GET['final']; // Connects to the database server $dbcnx = @mysql_connect($host, $user, $pass); if (!$dbcnx) { echo( "<P>Unable to connect to the database server at this time.</P>" ); exit(); } // Selects the database if (! @mysql_select_db($database) ) { echo( "<P>Unable to find database"); exit(); } //this is the command used to write the record into the MySQL database $query="INSERT into {$table} (name,roundOneTime, roundTwoTime,roundThreeTime, finalTime) VALUES ('{$one}', {$two}, {$three},{$four},{$five})"; //executes the command mysql_query($query) or die("Data not written."); echo("The data has been written to the table!"); ?>
- Next, upload the PHP file onto your website. Also, remember to fill in the following line correctly on the flash code shown here, or else the program will not work:
////insert in the location of the php script //////////
request.url = “insert the web address of php file here”; /////////////////////////////////////////////////////// - Now, go to Adobe Flash, and run the application by pressing CTRL + Enter. If you did everything correctly, then the text box should be populated with the following text:
The data has been written to the table.
Congratulations, you just used Flash CS3 (Actionscript 3.0) and PHP to write data to the MySQL database! Try to take a moment to examine the code to figure out how it was done.
- If the information above doesn’t appear, then that means that you have either imported the table incorrectly, did not assign the correct privileges to the user, or your information in the php file is incorrect. I recommend you go back and fix things before proceeding any further.
- So what exactly is going on here? Essentially, Flash is sending URL variables to the PHP script. The PHP script uses these variables and sends a query to the MySQL database to add a new record. After the data is successfully recorded into the MySQL database, the PHP script accordingly tells Flash that the data was successfully written.
- If you want to be sure that the data was actually written to the MySQL database. You can always use phpMyAdmin to check that the last entry in the table is what you expect it to be. I recommend that you do this to make sure that the record was actually written to the database.


I was not able to extract the zip file for this tutorial. It would be nice to have the original files. Thanks for all the hard work.
Sorry, we’re having some server issues. We are trying to resolve them ASAP.
man, i could rly use the source file…
i cant find out why Flash CS3 compiler gives me these errors:
1172: Definition fl.controls:TextInput could not be found.
1172: Definition fl.controls:TextArea could not be found.
aha! ive done it! thank you very very very much
btw quite funny that youve answered the guy sooner than he asked…
J
how did you figure it out?
i’ll have the source file uploaded and working at 1030pm pst. check back then!
You are God! OK, maybe just a minor deity.
to solve these errors:
1172: Definition fl.controls:TextInput could not be found.
1172: Definition fl.controls:TextArea could not be found.
simply add this at the top of your code:
import fl.controls.TextInput;
import fl.controls.TextArea;
wheen i say top of your code, i mean in frame 1 (if theres no class .as file) or if there is a class file that the code is done in, you would put it here:
package
{
import fl.controls.TextInput;
import fl.controls.TextArea;
public class ClassName …….
{
}
}
The source code can be downloaded but the fla file cannot be extracted… CRC error
What about if you put the imports in but it still throws that error?
just delete the import..not sure of the consequences,but it can run
Please write more tutes like this one your excellent !!
Excellent tutorial, thanks!
Can you briefly explain how would you pull an image from mysql and display it in flash? Thanks! -igor
Help. The program did work (go to http://newmedia.purchase.edu/~Jeanine/videoproject/choosevideoplay.html
but when I went in to make a slight change in the positioning of the FLVPlayback, Publish produces errors, namely 1172 Definition fl.video:FLVPlayback could not be found.
It was found before????
Now there was an Adobe update. Could that be the problem?
thanks in advance.
FOUND IT!
This was pretty subtle. The fl.video classes are only accessible if there is a FLVPlayback in the Library. Now, when I did this the first time, I had another .fla file open with a FLVPlayback component in its Library, so the Publish worked.
You and your tutorials have helped me before and I’m sure you will help me again.
Hi!
How can I chage highscore output that it puts scores in a different order.
The biggest score first and so on. I use it in a game where player needs to get as much points as he can. Thanks
You have to change the way you query the MySQL database in order to change the order. Maybe you can also change the order within flash. I haven’t coded in actionscript in a while, so I’m very rusty!
“You have to change the way you query the MySQL database” What I should do with the
database? Which parameters need to change? Im not a MySQL guru
I would suggest reading up on mysql basics.
Here’s a good place to start: http://www.webdevelopersnotes.com/tutorials/sql/mysql_tutorial_selecting_data_using_conditions.php3
Thanks! Now it works as it should be!
jgvasdkjcfjashvbcuyafcvsdcscas
no comments
no
hi i didnt see
Very nice
I am still struggling with this error
1172: Definition fl.controls:TextInput could not be found.
1172: Definition fl.controls:TextArea could not be found.
The lines
import fl.controls.TextInput;
import fl.controls.TextArea;
are in frame 1 and are at the top of the code. What the heck am I doing wrong. I am a newbie at ActionScript, I think I am missing something very basic that I just don’t have the background yet to understand.
Hi
To add an fl control it must be in ur library.
Thanks very much! Very very useful and good starting point to learn XML and PHP better. It helps when you’ve managed to make something very useful actually work, before learning more of the code. A base point to start from, where I can see the start to the finish…so thanks very much!
I had to delete the first 2 lines of the Actionscript files sometimes to make them work.
XYZ said: “to add an fl control it must be in ur library”.
Sorry but, how can I put it in the library?
Thanks
you should see all the controls in the Component window. If it’s not on the right side of the CS3 application, go to the menu above and select “Window” and then find “Component”.
The error with the lines
import fl.controls.TextInput;
import fl.controls.TextArea;
Can be resolved by putting a Dynamic text field on the stage with an instance name of ‘writingCompleted’ and changing the completeWriting function to this:
function completeWriting(event:Event):void {
writingCompleted.text = event.target.data;
}
I got this same error, and this was a workaround. Great tutorial though!
Доброго времени суток, форумчане сайта http://www.blinkdagger.com
Ответьте мне, пожалуйста, на несколько вопросов…
- какая программа умеет автоматически за НЕСКОЛЬКО СЕКУНД регистрировать ящики на mail.ru и многих других почтовиках?
- какая программа умеет автоматом рассылать по mamba.ru и loveplanet.ru по заданным параметрам, при этом еще поддерживая функции автоответчика?
- а также сможет разослать по форумам текст (например) “где купить валенки?”, а потом в ответ на этот текст ОТ ДРУГОГО имени и IP написать (например) “только на сайте megavalenki.ru!”?
- плюс распознаёт картинки и вопросы а-ля “что написано на этой картинке?”, “сколько будет 2+2?” и “какой сейчас год?” и умеет корректно на них отвечать?
- какая программа сможет разослать топики по форумам, попутно автоматически регистрироваться на них и создавая подробный отчет о проделанной работе?
- и при этом работает с разнообразными движками - phpBB, VBulletin, IPB, ExBB, Icon Board, YaBB, UltimateBB, множеством различных гостевых, досок и блогов?
- какую программу вы МОЖЕТЕ переделать под свой вкус?
- какая программа автоматически обновляет прокси / SOCKS, обеспечивая вам полную анонимность? (достаточно просто нажать ОДНУ кнопку)
- какая программа умеет рассылать персональные сообщения всем пользователям форумов phpBB, IPB, VBulletin?
- какая программа отсортирует Вашу базу ссылок по Google PageRank?
- какая программа МАССОВО отредактирует все Ваши ранее разосланные объявления по форумам?
- и при этом еще регулярно обновляется и совершенствуется.
Ответ ОДИН: всё это и многое другое под силу программному комплексу XRumer 4.085 Platinum Edition + Hrefer 2.85
Данный комплекс имеет множество отзывов на авторитетных источниках (Washington Post, Wikipedia и т.п.), имеет историю активного развития более 3-х лет.
Просто спроси у Яндекса!
См. также: массовые рассылки, распознавание текстовой защиты, мощная спамилка, PPC, дорвеи, софт для SEO, рассылка по форумам, программы для SEO, white SEO, XRumer Platinum, постинг, XRumer 2.9 устарел, хрумер 2.9 устарел, ППЦ, распознавание графической защиты, XRumer, рефспам, линкспам, хрумер 3.0 устарел, doorways, SEO, постинг по блогам, разослать по форумам и гостевым, софт для СЕО, белое СЕО, чёрное СЕО, программы для СЕО, black SEO, распознавание капчи, хрумер, суперсофт для SEO, СЕО
I get this error when trying to import sampleFlashDatabase.sql:
Error
SQL query:
– phpMyAdmin SQL Dump
– version 2.10.0.2
– http://www.phpmyadmin.net
–
– Host: localhost
– Generation Time: Sep 27, 2007 at 11:34 PM
– Server version: 5.0.37
– PHP Version: 4.4.4
SET SQL_MODE = “NO_AUTO_VALUE_ON_ZERO”;
MySQL said:
#1064 - You have an error in your SQL syntax near ‘SQL_MODE=”NO_AUTO_VALUE_ON_ZERO”‘ at line 2
I got it, it’s working great! I’m so happy!
Скажите, а у вас есть RSS поток в этом блоге?
Приветствую. А не подскажете, где можно найти такую же информацию, но только чтобы она была на английском языке
Good 235rter2rwer23r
Hi,
I’ve used your tutorial for the highscore system, is working fine but the only problem is that everytime i submit a new score I have to restart the Flash ide cause the new score is not displayed.
I mean the new scores are normally written to the db but parsing the xml file I’m always getting the first score table, the one not updated.
Any suggestions?
Thanks
This tutorial was great.
it was only a cache problem related to the xml…
now it works
I have a game already developed. What process would I use to use this within my already developed game? Thank you.
Bah… I went through all this just to realize that if I change my Actionscript to 3.0, Actions cannot be run from movie clips or instances. I think a lot of my game depends on that.
This just begs one question: how would you prevent hacked scores from entering the database? For example, if I were to open a browser and navigate to that URL with much-too-high scores, the database would insert a bogus record.
Also, make sure that you escape input before inserting a database record. (mysql_real_escape_string) Otherwise, your database could be compromised.
Хороший пост! Подчерпнул для себя много нового и интересного!
Пойду ссылку другу дам в аське
Автор, посты у вас, конечно, интересные. Но вы не думали поменять дизайн?
Так ведь без недостатков достоинства не так заметны
Все замечательно: и по стилю изложения, и по содержимому. Так держать!
Хм…, а я тут за свои годы, как-то привык ко всему этому, даже внимания на это не обращаю
Вы тоже привыкнете
Lol “Sorry, we’re having some server issues. We are trying to resolve them ASAP.” Lol ! 1 and a half year later… no answer!! LMAO!
Ой, благодарю
Давно искала эту информацию, спасибо.
Огромное человеческое спасибочки !
Огромное вам человеческое спасибо, очень актуальная заметка.
Что-то футер у вас вправо съехал (в опере при разрешении 1024х768)
[...] was creating my high scores based on this great tutorial I read some way back, but I wasn’t very satisfied with the overall performance of that [...]
[...] I visited. As usually, google was a big help. I found this great article from speckyboy magazine, 12 WP Plugins to Display and Highlight Code within your Blog, wich was all I needed to start. The problem now was chosing and testing the options [...]