Rabu, 01 Februari 2012

How To Create Login/Registration Using Flash with PHP and mySQL

For this Tutorial you will have to have some basic knowledge of PHP and mySQL, hopefully you won't need much though.  It is also assumed that you have a good understanding of Flash Actionscript.   What this tutorial basically does is to show you how to set up a table in a mySQL database, then using PHP (or asp with a few minor changes) manipulate that table and interact with Flash.  The first part of the Tutorial shows you how to create a unique user ID in the database, In this case it will be the persons name.  With a few minor changes however you'll be able to make it a secure password protected user login.  The unique user ID is required because in the next part we'll be saving the position of a couple movie clips and some of their property's.  In this way a user can return to the (your) site at anytime and the movie Clips will be in the exact same position that they left them in. I also added in a place for the user to add in a comment, which is also saved.  With a couple modifications you can turn that into a guest book or anything else you can think of.   This is a much more of a hands on tutorial so it's helpful if you follow the scripts and Fla source included, in addition to viewing the working example at the same time. 
It is recommended that you read over the PHP scripts first. These have all been extensively commented.  In PHP the # symbol is a comment.  Also it may be best to try to follow the code in the included Flash movie along as well.

 Go to setting mySQL database
You must have a mySQL server set up by your host or on your local machine.  I'll be using the most basic shell commands to set up the table. However their are GUI's out there to make this part easier.  Your host may already have one set up for you to use. Make sure to read all the documentation your host has available on using mySQL on their servers - some may be different.  But it should all basically be the same.
Once your database has been set up. Open up your shell account. In most cases you can use Telnet to get to your account.  From the telnet command prompt - type in mysql -p YourDatabaseName Then you will be prompted for a password. Type in your password.  You'll see some text appear after this, then the command prompt changes to read mysql> (then Type) use Database Name.  We will name the table saveMovie for this example. Then type in the following create table syntax exactly as it appears below:

You can then use the describe table command to see what the table looks like.
Here are a couple other mySQL commands you may find useful from the shell.
Change the Column Name:  mysql>alter table saveMovie change Name SomeotherName varchar(30);  (This just changes the name notice the syntax - after change enter the old Column Name followed directly after by the New column name and definition.
Delete one of the Columns: mysql>alter table saveMovie drop Name; This just deletes the column that you had previously named "Name".
Select and view everything in the Table: mysql>Select * from TableName;
Delete the whole table and start over: mysql>drop saveMovie;
Short List of Column types (note if the data that you have entered into one of these definitions is larger then the amount you specified in the table it will be cut off):
varchar (Number) - A variable text type - in my opinion the easiest and most flexible to use when first starting out. Maximum is 60 characters Long.
char (number) - A fixed character type column.
int (number) - A fixed integer type column. Default is 14 if you leave it blank.
text or blob - use either when you want to enter a large amount of text. 



Setting up the PHP 

The PHP scripts will be better explained by reading the comments in the attached files. Just open up the PHP script with notepad or any other text editor to make changes. 
The first thing we have to do is connect to the database.  You will need to know your database name, account username, and database password. In order to keep this as simple as possible use an include file to list these variables - They will be the same for each one of your scripts.  This is what is contained in the file Include.inc. One thing to note is that often times the $DBhost variable is slightly different then "localhost" - Sometimes it can be "localhost.yourHost.com".
create php script file save with name include.php
<?
$DBhost = "localhost";
$DBuser = "UserName";
$DBpass = "DatabasePassword";
$DBName = "DatabaseName";
$table = "saveMovie";
?>
Next you want to make a connection to the Database: 
mysql_connect($DBhost,$DBuser,$DBpass);
@mysql_select_db("$DBName");
 You can see how the variables in the Include File are used here. I'm only going to go over in detail the SQL query part of each script. The rest you should be able to figure out by reading through the comments in the File. Also note that for simplicity some basic sercurity precautions where left out. These are not necessary but you might want to include them if you have any type of sensitive data.

User Registration

PHP used in the first Registration section

$query = "INSERT INTO $table (Name, Object1, Object2, Object3, Comment) VALUES 
('$RegName' , '', '', '', 'Hello')";
$result = mysql_query($query);
 This will create a new entry in the database for a new user.  The only value we have to worry about for now is the Name variable which will be set to the Name entered in the Flash Movie in the text field Named RegName.  All other variables will be set later.  The name column was defined as being unique when we created the mySQL table so there can only be one User with that Name.  If someone else try's to register with that name they will not be able to. The second line of the above code is what actually performs the query.  The only thing that's returned to the Flash movie at this point is a message to the user proclaiming that registration was successful - Or failed if the Name already exists in the database. You can see how this is done in the actual script.

Flash Actionscript Used in Registration

All that is required in Flash at this point is to have one text Field Named RegName - Then either on a button or Frame command this Code.
on (release) {
 Status = "Beginning registration Process... Please Hold";
 loadVariablesNum ("Register.php?RegName="+RegName, 0);
}
I have an extra text field named Status - but this is optional.  Notice on the LoadVariablesNum command I specifically pass the variable RegName to the PHP script.  This is not necessary, adding "Post" will do the same thing. It's just sometimes easier to keep track of what's passed to a script in this way. After a user has entered their Name and hit the register button the LoadVariablesNum Command will call the PHP script, pass whatever was entered in the RegName Field to it and execute the statements. 

User Login

PHP used in Login (Login.php)

$query = "SELECT * FROM $table WHERE Name = '$Name'";
$result = mysql_query($query);
$numR = mysql_num_rows($result);
#If the number of rows is not equal to one then it prints out an error statement - Name not in Database. 
 if ($numR == 1) { 
 print "_root.Status=Success Login Complete&_root.CheckLog=1";
 }
 else {
 print "_root.Status=Failure - Your name was not found - Please register"; 
 }
The first 2 lines of this code preforms the query on the database. It selects the record where the Name entered in the Flash movie is equal to a unique name found in the database.  The next line of code (excluding the comment) checks to see if a record was returned. If a record is returned then the Login is a success.  Then it prints out the results back to flash.  I also pass back another variable to tell the movie if the Login was successful. In this case I named it CheckLog.  The movie will keep looping the second and third frame until it successfully tests that the variable CheckLog is not equal to nothing ie it's now equal to 1.

Actionscript used in Flash for Login

on (release) {
 gotoAndPlay(2);
 Status = "Beginning Login Process.. Please Hold";
 loadVariablesNum ("Login.php?Name="+Name, "0");
}
 This is the actionscript on the Login Button.  Initially the movie stops at the first frame of the root of the movie.  After you hit the Login button it goes to frame 2 and continues to Loop until it finds that there is a value for CheckLog.  The Check part looks Like the following.
if (CheckLog ne "") {
gotoAndPlay (4);
}else {
gotoAndPlay(2);
}
That's it.  After a user has successfully Logged in we can Load the variables for the first Time.  At first they won't have any values. So they come to rest at the default location

 Create Load.php

<?php
/* The login script accesses the database and checks to see whether your Login name exists. If it does it will select your information from the database and Print it out back to Flash. */

/* This first line of Code is to load your database variables - The include File should be renamed with your database variables.*/

require 'include.php';

/* This line of Code changes the name to all UPPERCASE. This is so that the login Name is not case sensitive. You can make it case sensitive by leaving this line out.*/
$Name = strtoupper ($Name);

/* This line takes out everything from the $Name variable that is not a captital or lowercase letter or a interger between 0 and 9.  This line is only for security purposes so that users can not enter anything that could disrupt the database. You can take this line out if you want.  Or you can allow users to enter other symbols by including a \ followed by that character right after.*/

$Name = ereg_replace("[^A-Za-z0-9 ]", "", $Name);

// Connects to the database.
mysql_connect($DBhost,$DBuser,$DBpass);
mysql_select_db("$DBName");

// The SQL query
$query = "SELECT * FROM $table WHERE Name = '$Name'";
$result = mysql_query($query);

/* This just gets the number of rows in the Query - It's just a check to see if the Name exists - If not it prints out an error statement. */
$numR = mysql_num_rows($result);

// If the number of rows is not equal to one then it prints out an error statement - Name not in Database.
   
    if ($numR == 1) {
    print "Status=Success Login Complete&CheckLog=1";
    }
    else {
    print "Status=Failure - Your name was not found - Please register";
    }

?>

2 komentar:

  1. Waow.. Keren.. Penggunaan bahasa inggris yang sempurna.
    Dan untuk masalah php ataupun asp, terima kasih saja untuk informasinya. Ini sangat bermanfaat.

    BalasHapus
  2. Wow, marvelous blog format! How long have you been blogging for? you make running a blog glance easy. The total glance of your website is excellent, let alone the content material!
    Create a MySQL database.

    BalasHapus