Creating High Score / Top Scores / Data Table in Adobe Flash CS3
15 Oct 2007 Quan Quach 55 comments 11,385 views
Part 4: More on Sending Data to/from Flash via PHP
In Part 2, we recorded an entry into the MySQL database. In Part 3, we essentially retrieved data from the MySQL database. In the final part of this tutorial, we will continue to explore how Flash/PHP/MySQL interact. Specifically, I will explain how to determine and display the ranking of the user at the end of each round, relative to all the records in the database.

Let’s get started. First, Flash sends data to the PHP script. The PHP script then queries the MySQL database and obtains the information desired. This information is returned to the flash application, informing the user what rank was received relative to all the records in the database. The flow chart below might help you visualize the process.

- Open up a new Flash File (Actionscript 3.0). Press F9 and paste the following code into the Actions – Frame. This code uses URL variables to send data to the PHP script.
import fl.controls.TextInput; import fl.controls.TextArea; var variables:URLVariables = new URLVariables(); //specifies the URL variables that will be used variables.playerTime = 1.03; variables.roundNum = "roundOneTime"; var request:URLRequest = new URLRequest(); ////insert in the location of the php script ////////// request.url = "insert web address of php file here"; /////////////////////////////////////////////////////// request.data = variables; var loader:URLLoader = new URLLoader(); loader.load(request); //after event is completed, goes to the function displayRanking loader.addEventListener(Event.COMPLETE,displayRanking) function displayRanking(e:Event):void { //creates a textbox to display text data var displayRank:TextField = new TextField; displayRank.autoSize = "center"; displayRank.x =200; displayRank.y= 200; displayRank.text = e.target.data; addChild(displayRank); }
- The following script is used to determine the ranking of the current player after every round. 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 /////////////////////// fill in this information here ///////////////////// $host = ""; $user = ""; $pass = ""; $database = ""; $table = ""; ///////////////////////////////////////////////////////////////////////////// //get the URL variables and store them into PHP variables //that can be used here in this script $playerTime = $_GET['playerTime']-.0001; //to correct precision problems $round = $_GET['roundNum']; $linkID = mysql_connect($host,$user,$pass) or die("Could not connect to host."); mysql_select_db($database, $linkID) or die("Could not find database."); $query="SELECT * FROM {$table}"; $result=mysql_query($query); $num=mysql_numrows($result); $num= $num+1; //this variables holds the number of entries in the database + 1 $query2= "select * from {$table} where {$round} < {$playerTime}"; $result2= mysql_query($query2,$linkID) or die("Data not found."); $rank = mysql_numrows($result2); $rank = $rank + 1; //this variable holds the #of lower than the current time +1 echo("You are rank {$rank} out of {$num} for this round!"); ?>
- Next, upload the PHP file onto your website. Also, be sure to fill in the following line correctly on the flash code:
////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. If you did everything correctly, then you should see the following:
You are rank 211 out of 443 for this round!
You can go back into the code and change the playerTime variable to confirm that the ranking changes with different times.
- 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.
- So what exactly is going on here? Essentially, Flash is sending URL variables to the PHP script, which in turn queries the MySQL database. The MySQL database returns the requested data to the PHP script, which then goes back to the Flash application to be displayed.
End of Tutorial


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 [...]