[h1]
Flash - MySQL Integration[/h1]
In this tutorial, I will show you how to make a basic Login / Register using Flash. This will allow you to have Flash actually communicate with a MySQL database, get data from it, and also write data to it!
What you'll need- Access to a MySQL database (phpMyAdmin)
- Knowledge of basic MySQL (not required, but still good to know)
- Knowledge of basic PHP
- Access to the FTP of a server (to upload your PHP files)
- Flash knowledge (how to make buttons, variables, functions, and some basics)
It may not seem like much, but it can let you make some pretty powerful stuff.
Lets get startedOkay, let me clear something up first. Flash can't 'communicate' with MySQL DIRECTLY! Here's how it works:
Flash --> PHP --> MySQL --> PHP --> FlashBut, the question is, how can Flash 'communicate' with PHP?
The answer: Simple! loadVars(); and sendAndLoad(); !
But before I get really into this, let's start be setting everything up.
The setup-MySQL (cpanel)If you have a cpanel, open it up, log in, and go to phpMyAdmin, if you don't skip to the next section. Here, you can manage your databases and tables. My phpMyAdmin looks like this
[screen shot].
Now, go into the database of your choosing, and look for this

.
Have it look like this
.JPG)
.
Once you're done with that, press 'ok', it'll go to a page like this
[screen shot].
Sadly, there are a lot of forms to put in, so mine got cut off, but you get the idea. Here's the fields that we need to modify:
- Field - The name of the 'column'
- Type - What type of data is in the field
- Length/Values - How long can the date be (how many digits / characters)
- Extra - auto_incriment - increase by '1' automatically.
Here's what we need to fill in for the data:
Going from top to bottom, starting in the first column (the "Field" one), enter in this data:
Now, go over to the second column, Type (it's a dropdown):
Go to the third column, Length/Values:
Skip the next 4 columns, and go right to Extra, in this one, just do this:
- auto_increment
- LEAVE BLANK
- LEAVE BLANK
- LEAVE BLANK

Now, there's about 4 radial buttons, and one checkbox, in the first row, select the radial button with the key on it, which means it's primary. In the second row, select the one with the U, that's Unique, which means that there can't be 2 with the same value. The third row, leave blank (at ---), and in the forth, leave blank (at ---).
The setup-MySQL(pure PHP)*ONLY IF YOU CAN'T DO THE phpMyAdmin (above)!!!*If you have access to a database, make a PHP file with this code:
<?php
//Connect to database
define ( 'DB_USER', '[username]' );
define ( 'DB_PASS', '[password]' );
define ( 'DB_DB', '[database]' );
define ( 'DB_HOST', 'localhost' );
mysql_connect(DB_HOST,DB_USER,DB_PASS) or die("Error connecting to Database! Please Try again." . mysql_error());
mysql_select_db(DB_DB) or die("Cannot select database! Please Try again." . mysql_error());
//Run query
mysql_query("CREATE TABLE `users` (`id` INT( 10 ) NOT NULL AUTO_INCREMENT ,`username` VARCHAR( 32 ) NOT NULL ,`password` VARCHAR( 32 ) NOT NULL ,`email` VARCHAR( 255 ) NOT NULL ,PRIMARY KEY ( `id` ) ,UNIQUE (`username`)) TYPE = MYISAM");
mysql_close();
?>
Then, upload it to your site, and open it ONCE, now, if no errors occur, the table is created.
Making login_register.phpOkay, open up notepad,
notepad 2,
Araneae,
Dreamweaver, whatever you use to program with PHP, personally, I like notepad 2.
Now that you've got your program open, add this PHP:
<?php
define ( 'DB_USER', '[username]' );
define ( 'DB_PASS', '[password]' );
define ( 'DB_DB', '[database]' );
define ( 'DB_HOST', 'localhost' );
mysql_connect(DB_HOST,DB_USER,DB_PASS) or die("Error connecting to Database! Please Try again." . mysql_error());
mysql_select_db(DB_DB) or die("Cannot select database! Please Try again." . mysql_error());
/*
- ! - ! - Variables set in PHP
$correct
$qResult
$nRows
$rString
$check_user
$reg_ok
$reg_msg
- ! - ! - Variables set in Flash
$user
$pass
$reg_user
$reg_pass
$reg_mail
$sql_type
*/
//Login Script
if ($sql_type == 0){
$qResult = mysql_query("SELECT * FROM `users` WHERE `username` = '$user' AND `password` = '$pass'");
$nRows = mysql_num_rows($qResult);
$rString = "&n=".$nRows."&<br>";
if ($nRows > 0){
$correct = 1;
$rString .= "&correct=".$correct."&<br>";
}
echo $rString;
//Register Script
} else if ($sql_type == 1){
$check_user = mysql_query("SELECT * FROM `users` WHERE `username` = '$reg_user'");
$check_user_row = mysql_num_rows($check_user);
if ($check_user_row > 0){
$reg_ok = 0;
$reg_msg = "Sorry, that username is not unique!";
$rString = "®_ok=".$reg_ok."&<br>®_msg=".$reg_msg."&<br>";
} else if ($check_user_row <= 0){
//Make account
mysql_query("INSERT INTO `users` (`id` , `username` , `password` , `email`) VALUES ('', '$reg_user', '$reg_pass', '$reg_mail')");
$reg_ok = 1;
$reg_msg = "congratulations! Your account has been created successfully! Press 'Return' to go back to the main login screen, and log into your account!";
$rString = "®_ok=".$reg_ok."&<br>®_msg=".$reg_msg."&<br>";
}
echo $rString;
}
?>
Okay, I know it's a bit confuzzling, but let me explain it:
define ( 'DB_USER', '[username]' );
define ( 'DB_PASS', '[password]' );
define ( 'DB_DB', '[database]' );
define ( 'DB_HOST', 'localhost' );
mysql_connect(DB_HOST,DB_USER,DB_PASS) or die("Error connecting to Database! Please Try again." . mysql_error());
mysql_select_db(DB_DB) or die("Cannot select database! Please Try again." . mysql_error());
This is basically connecting to the database. You have to fill in where it says 'username', 'password', and 'database'!
/*
- ! - ! - Variables set in PHP
$correct
$qResult
$nRows
$rString
$check_user
$reg_ok
$reg_msg
- ! - ! - Variables set in Flash
$user
$pass
$reg_user
$reg_pass
$reg_mail
$sql_type
*/
This is just me, putting in what the variables are, and where they come from. So I don't mess up and use a variable in PHP that will later be imported form flash.
//Login Script
if ($sql_type == 0){
$qResult = mysql_query("SELECT * FROM `users` WHERE `username` = '$user' AND `password` = '$pass'");
$nRows = mysql_num_rows($qResult);
$rString = "&n=".$nRows."&<br>";
if ($nRows > 0){
$correct = 1;
$rString .= "&correct=".$correct."&<br>";
}
echo $rString;
This is the login script. When I'm in flash, I'll have it send the variable "$sql_type", which will tell the PHP script weather to register, or login. In this case, if the $sql_type is 0, it will run the login script. Here's how the login script works:
$qResult = mysql_query("SELECT * FROM `users` WHERE `username` = '$user' AND `password` = '$pass'");
That sets the query to a variable, and the $user, and $pass are the variables imported form Flash. This query selects every row, where the field username, is equal to the variable $user, that was imported form flash, AND it checks if the passwords match, assuring it to be the right account.
$nRows = mysql_num_rows($qResult);
This takes the results of the query (that variable I set earlier), and checks to see how many rows were selected (That's why it's SELECT * FROM table name)
$rString = "&n=".$nRows."&<br>";
the variable $rString is what flash will take in. When you use loadVars in flash, it reads variables inside ampersands (& <-- and sign), so I set the variable 'n' to the number of rows, just incase I need to know how many rows were resulted form the query. If I were to echo $rString right now, it'd come out as this:
&n=0&
Because there isn't any data in the table, whatever I'd search for, would come up as nothing!
if ($nRows > 0){
$correct = 1;
$rString .= "&correct=".$correct."&<br>";
}
This is where I check to make sure the query came up with anything, if it did, then that means you got a correct login, and the usernames and passwords, matched up with those in the database! Then, it adds another variable to the string, $correct, now if I were to echo $rString, it'd come out like this:
&n=0&
&correct = 1&
Because it worked!
echo $rString;
And finally, I ACTUALLY echo $rString!
//Register Script
} else if ($sql_type == 1){
$check_user = mysql_query("SELECT * FROM `users` WHERE `username` = '$reg_user'");
$check_user_row = mysql_num_rows($check_user);
if ($check_user_row > 0){
$reg_ok = 0;
$reg_msg = "Sorry, that username is not unique!";
$rString = "®_ok=".$reg_ok."&<br>®_msg=".$reg_msg."&<br>";
} else if ($check_user_row <= 0){
//Make account
mysql_query("INSERT INTO `users` (`id` , `username` , `password` , `email`) VALUES ('', '$reg_user', '$reg_pass', '$reg_mail')");
$reg_ok = 1;
$reg_msg = "congratulations! Your account has been created successfully! Press 'Return' to go back to the main login screen, and log into your account!";
$rString = "®_ok=".$reg_ok."&<br>®_msg=".$reg_msg."&<br>";
}
echo $rString;
}
?>
Now for the register script!
//Register Script
} else if ($sql_type == 1){
First, if $sql_type isn't 0, and it IS 1, then it will run the Register script.
$check_user = mysql_query("SELECT * FROM `users` WHERE `username` = '$reg_user'");
$check_user_row = mysql_num_rows($check_user);
Here, it makes another query, to check the username. So, it selects the rows where the field username, is the same as what the register username is, and it counts how many rows were returned.
if ($check_user_row > 0){
$reg_ok = 0;
$reg_msg = "Sorry, that username is not unique!";
$rString = "®_ok=".$reg_ok."&<br>®_msg=".$reg_msg."&<br>";
If it does come up with rows, then that means that you didn't enter in a unique username! So, it sets $reg_ok, which will tell flash if the registration worked okay, to 0, because it didn't work! Them, it makes the registration message (will be used in flash) return the error, in this case, "Sorry, that username is not unique!". And, finally, it compiles the string to be printed. If I were to echo THIS $rString, it'd come out like this:
®_ok=0&
®_msg="Sorry, that username is not unique!"
} else if ($check_user_row <= 0){
//Make account
mysql_query("INSERT INTO `users` (`id` , `username` , `password` , `email`) VALUES ('', '$reg_user', '$reg_pass', '$reg_mail')");
Now, if the variable $check_user_row is less than 0, meaning it didn't select ANY rows, it will tell PHP to do this:
mysql_query("INSERT INTO `users` (`id` , `username` , `password` , `email`) VALUES ('', '$reg_user', '$reg_pass', '$reg_mail')");
This is a query that tells the table you created earlier to insert some data, and that data is taken right from Flash!
$reg_ok = 1;
$reg_msg = "congratulations! Your account has been created successfully! Press 'Return' to go back to the main login screen, and log into your account!";
$rString = "®_ok=".$reg_ok."&<br>®_msg=".$reg_msg."&<br>";
}
echo $rString;
And, finally, it sets $reg_ok to 1, because the registration works, and it sets $reg_msg to the completion message, then prints $rString.
Time for Flash!Okay, now for the fun-ish part, Flash!
Make a 200x200 flash, and style it how you like.
I liked to use components, because they're easy to work with, and require little fussing, so drag in a few components (button and text input for now).
Here's how I made my login look:

if you're wondering, that's a dynamic text above everything, so add one of those too!
Now, to set up the instance names. In the top dynamic textbox, set it up like this:

Now, for those two input text components. For the username one, insert 'user_name' as the instance name.
For the password one, insert 'pass_word' as the instance name, and go to 'Parameters', make it be pass worded, so the characters come up as *s.
The two buttons have no instance name, just the labels are change, so, again, in 'Parameters', change the label.
For the actions on the 'Login' button, put this:
on (click) {
_root.login();
}
onClipEvent (enterFrame) {
this.tabEnabled = false;
}
For the 'Register' button, put this:
on (click) {
_root.gotoAndStop("register");
}
onClipEvent (enterFrame) {
this.tabEnabled = false;
}
For the 'user_name' input text field (the component), put this as action script:
onClipEvent (enterFrame) {
this.tabEnabled = true;
}
And the same for 'pass_word'.
All the 'tabEnabled', means when you press 'tab', it will go to that field.
Now, create an MC, and put whatever you want in it, it doesn’t matter, and put it off stage. Give it these actions:
onClipEvent (enterFrame) {
_root.welcome_msg.text = "Please Login";
}
That will set what the dynamic text says
Finally, the actions on the main frame:
stop();
//Set variables
var loadVars_in:LoadVars = new LoadVars();
var loadVars_out:LoadVars = new LoadVars();
//When the variables get loaded IN form PHP, check if it successfully loaded
loadVars_in.onLoad = function(success) {
if (success) {
//If it was successful
//Convert the variables form the PHP, into flash ones
_root.correct = this["correct"];
//And stop on the 'home' frame
_root.gotoAndStop("home");
} else {
//And if it failed, give the user testing it from flash, which it failed
//so you can look over your PHP
trace("FAILURE");
}
};
//This is the login function
function login() {
//Sets a variable to the user_name component's text
u_name = String(user_name.text);
//Sets a variable to the pass_word component's text
p_word = String(pass_word.text);
//Sets the loading out variable 'user' to whatever u_name is
//That's why PHP read that value $user as the one from flash
//Because the output variable has the sub variable 'user'!
loadVars_out.user = u_name;
//Same for password
loadVars_out.pass = p_word;
//Set the sql_type variable so PHP knows weather to login, or register
//in this case, 0 for login!
loadVars_out.sql_type = 0;
//And, finally, sendAndLoad!
//Confusing script eh? Well, here's send and load:
//"/login_register.php" your URL to the PHP file
//loadVars_in <-- the flash variable that will take the response
//from PHP, and put it in flash
//"POST" <-- the method of exporting the variables!
loadVars_out.sendAndLoad("/login_register.php", loadVars_in, "POST");
}
All of the scripts are explained in // <-- comments!
Now, insert a new keyframe, and label it 'home'
Okay, here's what I have on the 'home' frame:

Those are 2 textboxes, each formatted. Select the top one is an EXACT copy as the one from frame 1, but the second one needs to be changed a little. Make the properties exactly like this:

Now, I've added another component, the UI-Scrollbar. Drag one in, and give it these parameters:

Next, remember that useless MC with some actions on it? Well, put it in this frame too, but give it these actions:
onClipEvent (enterFrame) {
if (_root.correct == 1) {
_root.welcome_msg.text = "Welcome "+_root.loadVars_out.user;
_root.main_menu.text = "Well, you've made an account and logged in! This is it so far, because this is just the test one, but still, congrats, "+_root.loadVars_out.user;
_root.back_button.enabled = false;
} else {
_root.welcome_msg.text = "Sorry!";
_root.main_menu.text = "It appears as though you've entered an incorrect username or password! Press the button below to return and try again!";
_root.back_button.enabled = true;
}
}
Basically, that's just what happens if they login, or not (if it was an invalid user / pass)
Finally, there's a return button. Add these actions to it:
on (click) {
_root.gotoAndStop(1);
}
And give it the instance name 'back_button'.
On to frame 3! give it the label 'register'.
I have my register frame set up like this:

And, again, that's the SAME dynamic text up top!
The three input text components have these instance names:
new_user
new_pass
new_email
I'll let you guess what goes where XD
Oh, and on the 'new_pass', be sure to make it pass worded, so the characters are *.
Now, again, there's that nice useless Movieclip that's off stage! Give it these actions:
onClipEvent (enterFrame) {
_root.welcome_msg.text = "Registration";
_root.user_user = _root.new_user.text;
_root.user_pass = _root.new_pass.text;
_root.user_email = _root.new_email.text;
}
That sets some variables, nothing incredible.
Finally, the Register button, here's the actions:
on (click) {
_root.gotoAndStop("reg_eval");
}
That's it for frame 3! On to the final frame, frame 4!
Insert the keyframe for frame 4, and give it the label 'reg_eval'.
My frame looks like this:

Again, that's the SAME dynamic text up top.
The second dynamic text, however, is different, here's the properties:

And that scrollbar, had these properties:

Almost done! Now, for the two buttons on the bottom, the first is named:
back_button
And has these actions:
on (click) {
if (this.label == "Back") {
_root.gotoAndStop("register");
} else if (this.label == "Register") {
_root.register();
}
}
And the second has these actions:
on (click) {
_root.gotoAndStop(1);
}
Okay, again, that useless Movieclip comes into play, with these actions:
onClipEvent (load) {
//set some text
_root.reg_eval.text = "Press the 'Return' button to go back to the main menu."+newline+newline;
e = 0;
i = 0;
q = 0;
}
onClipEvent (enterFrame) {
_root.welcome_msg.text = "Registration";
//one error check
if (q == 0) {
//check if the username field is filled
if (i == 0) {
if (!_root.user_user) {
_root.reg_eval.text += "Please fill the 'Username' field, press the 'Back' button to go back to registration."+newline+newline;
e = 1;
}
i++;
}
//check if the password field is filled
if (i == 1) {
if (!_root.user_pass) {
_root.reg_eval.text += "Please fill the 'Password' field, press the 'Back' button to go back to registration."+newline+newline;
e = 1;
}
i++;
}
//check if the username field is at least 2 characters long
if (i == 2) {
if (_root.user_user.length<2) {
_root.reg_eval.text += "Your username must be at least two characters long, press the 'Back' button to go back to registration."+newline+newline;
e = 1;
}
i++;
}
//check if the email field is filled
if (i == 3) {
if (!_root.user_email) {
_root.reg_eval.text += "Please fill the 'eMail' field, press the 'Back' button to go back to registration."+newline+newline;
e = 1;
}
i++;
}
//if there are no errors, then set the register to be enabled
if (e == 0) {
_root.reg_eval.text = "There have been no errors detected in your registration form, please press 'Register' to complete your registration.";
_root.back_button.label = "Register";
q = 1;
}
}
//check if the registration works, disable the back button
if (_root.reg_ok == 1) {
_root.back_button.enabled = false;
} else {
_root.back_button.enabled = true;
}
}
And, the heavy hitter, the actions on the frame:
stop();
//Set variables
var regVars_in:LoadVars = new LoadVars();
var regVars_out:LoadVars = new LoadVars();
//check for success
regVars_in.onLoad = function(success) {
if (success) {
//set imported variables to local ones
_root.reg_ok = this["reg_ok"];
_root.reg_eval.text = this["reg_msg"];
} else {
trace("FAILURE");
}
};
//The register function
function register() {
//convert the strings, just like for login
u_name = String(user_user);
p_word = String(user_pass);
e_mail = String(user_email);
//set the variables, like login again
regVars_out.reg_user = u_name;
regVars_out.reg_pass = p_word;
regVars_out.reg_mail = e_mail;
//change sql_tyoe to 1, because we're doing register
regVars_out.sql_type = 1;
//and set the sendAndLoad function
regVars_out.sendAndLoad("/login_register.php", regVars_in, "POST");
}
It's just like login, but with a few more variables!
Now, go forth, and test your flash, but be warned! It must be uploaded on the server first, because of "/login_register.php", oh, and that URL can be DIRECTLY to your uploaded PHP file, this was just for example!
Here's my result:
http://adamsstupidideas.com/sticktoons/mmorpg%20files/Register%20+%20Login.swfIf you like this tutorial, please
Click Here to register.
Click the link below to download the Flash file for this tutorial.
How to make Flash 'communicate' with MySQL ZIP