1. Code
  2. JavaScript

Create a Comment Form with Flash, PHP, XML and MySQL

Scroll to top
15 min read

In this tutorial, I'll show you how to use Flash, PHP and MySQL together. We'll build a simple comment form that takes entries and stores them in a database. We'll use PHP to retrieve the entries and format the comments into XML form. Let's get going!

Step 1: Create the Flash File

Start up Flash and create a new Flash file(ActionScript 3.0). Create a new folder and save the file into the folder as "commentForm.fla". Next create a new ActionScript File. Save the file into the same folder as "commentForm.as".

Step 2: Setting the Stage

Open your newly created Flash document, then in the properties panel, change the size of the stage to 960x400 pixels. Also, in the Document class text box, type in "commentForm". This will link the external ActionScript file with our Flash document.

Step 3: The Background

Select the Rectangle tool and draw out a retangle with a stroke of any size. Select the whole rectangle and open the Align panel by going to Window > Align. In the Align panel, under "Match size", click the "Match width and height" button. This will scale the rectangle to the size of the stage. Still in the Align panel, under "Align", click the "Align left edge" and "Align top edge" buttons. This will move the rectangle to the top-left of the stage.

Next, select the fill portion of the rectangle. In the Color panel, select the linear gradient as the fill color. With the rectangle still selected, select the Gradient Transform tool and rotate the gradient 90 degrees (make sure the black side is facing towards the bottom). Under the gradient color options, give the white portion a color of #F2F2F2. Then, give the black side a color of #D9D9D9. Finally, select the stroke, give it a color of #999999, and in the properties panel, give it a size of 2.

Lastly, select the whole rectangle and convert it into a movieclip. Go into the Filters window, click on the plus icon and give the movieclip a Glow. The Glow should have a 10 for Blur X and Blur Y, Strength of 33%, Quality of High, Color of black and make sure to check the Inner glow box. The rectangle movieclip should have a slight inner glow now.

Step 4: Adding the Components

Select the Text tool. In the properties panel, select Dynamic Text, make sure the color is black, font of "Arial", and font size of 10. On a new layer, draw out a text box that is 41.9px wide and a height of 15.2px. Give the text box an X position of 18 and a Y position of 6.3. Finally, give the text box an instance name of "nameText".

Create another text box on the stage. This text box will have a width of 246.9, a height of 17.4, a X position of 18, a Y position of 22.9, and an instance name of "nameField".

Now create another text box with a width of 41.9, height of 15.2, X of 18, Y of 42.4, and instance name of "emailText".

Make another (nearly there) text box with a width of 246.9, height of 17.4, X of 18, Y of 58.9, and instance name of "emailField".

Once again, create a text box with a width of 55.5, height of 15.2, X of 18, Y of 80.1 and instance name of "commentText".

Finally, make one more text box. Give it a width of 466.9, height of 260.9, X of 18, Y of 96.3 an instance name of "commentField", and set the Maximum characters field to 1000. In the text box with the name "nameText", give it a value of "Name". Next, select the "emailText", and give it a value of "Email". Finally, select the "commentText" text box, and give it a value of "Comment". We'll be changing the text color of these text boxes dynamically.

Create another dynamic text box. Give it a width of 421.1, a height of 211.4, X of 521.3, Y of 144.6, and instance name of "area". Select all four empty dynamic text boxes, and in the properties panel, change their font size to 12. Only the label text fields should have a font size of 10. Select the text tool again. In the Properties panel, change the type back to Static, color is black, font is "Arial", and font size is 10. Create a static text box. Give it a width of 5.2, height should default to 15.2, X of 520.5, Y of 11.1 and give it a value of "Comments".

Next, navigate to the Components panel. Drag an instance of the List component onto the stage. Give the List component a width of 422.9, height of 100, X of 520, Y of 27.8 and an instance name of "list".

Drag a copy of the Checkbox component onto the stage. Give it a width of 100, height of 22, X of 280.3, Y of 57.4, instance name of "newsletter", and, in the Parameters panel, give it a label of "Newsletter". Lastly, create one more dynamic text field. Make sure it has a color of black, font is "Arial",and the font size is 10. Give it a width of 128, height of 15.2, X of 356.9, Y of 367.6 and instance name of "dyTex".

Step 5: Adding the Component Backgrounds

The next step is create the graphics underneath the text boxes. Create a new layer and move it below the layer with the text fields. Select the Rectangle tool. In the properties panel, give it a stroke of 2. Make sure the stroke's color is #CCCCCC. Give the rectangle a fill of white. In the rounded corners box, give it a value of 10.

Draw out a rectangle that has a width of 466.9, a height of 260.9. Select the whole rectangle and convert it to a movieclip. With the movieclip selected, go to the Filters tab. Give the rectangle a new Dropshadow filter. The new filter will have a 6 for Blur X and Blur Y, a Strength of 66%, a Quality of High, an Angle of 90, a Distance of 1, a Color of black, and check the box next to Inner shadow. Finally, give the rectangle movieclip a X position of 18 and a Y position of 96.3.

Next draw out another rectangle with the same styles applied. This time, give the rectangle a width of 422.6, height of 214. Convert it into a movieclip. Then give the movieclip an X of 520.5 and a Y of 143.3. Apply the same filter as the previous rectangle.

Now we're going to create another rectangle. This time give the rounded corners a value of 5; leave all the other parameters the same. Draw a rectangle that has a width of 246.9, and a height of 17.4. Turn it into a movieclip and give it an X value of 18 and a Y of 22.8. Next, go to the Filters tab and apply a Dropshadow filter. Give the filter a Blur X and Blur Y value of 4, Strength of 66%, Quality of High, Color of black, Angle of 90, Distance of 1, and check the box next to Inner shadow. Select the movieclip and duplicate it. Give the next movieclip a X of 18, and Y of 58.9.

Step 6: The Final Touches

Take the Rectangle tool one more time. Make sure that there is still a value of 5 for the rounded corners and draw a rectangle that is 99 wide and has a height of 20.6. Convert this shape into a Button. Enter the edit mode of the button and add a new layer. Grab the Text tool and create a static text box with a value of "Submit". Give the new button a X of 18.3, Y of 367.6, and an instance name of "button".

Finally, select the Line tool. Give it a stroke size of 1 and a color of #999999. Draw a line on the stage. Select the line and give it a height of 327, X of 502.4, and Y of 28.2. Duplicate the line and move it over one pixel to the right and give it a color of white. The application is fully designed now.

Step 7: The Document Class Skeleton

Navigate over to the ActionScript file that was created at the beginning of this tutorial. Paste this code into it.

1
2
package {
3
	
4
	import flash.display.Sprite;
5
6
	public class commentForm extends Sprite
7
	{
8
		
9
		public function commentForm()
10
		{
11
			
12
		}
13
	}
14
}

Step 8: The Imports

Here are the import statements that we're going to use. Paste them in below the package declaration and above the class declaration. Also, we list out the variables we're going to use.

1
2
package {
3
	
4
	import flash.display.Loader;
5
	import flash.display.MovieClip;
6
	import flash.display.SimpleButton;
7
	import flash.display.Sprite;
8
	import flash.events.Event;
9
	import flash.events.FocusEvent;
10
	import flash.events.IOErrorEvent;
11
	import flash.events.KeyboardEvent;
12
	import flash.events.MouseEvent;
13
	import flash.external.ExternalInterface;
14
	import flash.net.URLLoader;
15
	import flash.net.URLRequest;
16
	import flash.net.URLRequestMethod;
17
	import flash.net.URLVariables;
18
	import flash.text.TextField;
19
20
	public class commentForm extends Sprite
21
	{
22
		private var tf:TextField;
23
		private static const URL:String = "YOUR_SERVER";
24
        
25
		public function commentForm()
26
		{
27
			
28
		}
29
	}
30
}

Step 9: The Init Function

Here, we are setting the event listeners and word wrapping for the large text fields. Also we call the onComplete and onInput functions. The onComplete function will load the XML from the database. This way the list component is populated when the application starts. With the onInput function, we set the dyText text field with proper value.

1
2
		public function commentForm()
3
		{
4
			init();
5
		}
6
        private function init():void
7
		{
8
			commentField.addEventListener(FocusEvent.FOCUS_IN, onFocus);
9
			emailField.addEventListener(FocusEvent.FOCUS_IN, onFocus);
10
			nameField.addEventListener(FocusEvent.FOCUS_IN, onFocus);
11
			commentField.addEventListener(KeyboardEvent.KEY_DOWN, onInput);
12
			commentField.addEventListener(KeyboardEvent.KEY_UP, onInput);
13
			button.addEventListener(MouseEvent.CLICK, onClick);
14
			onComplete(null);
15
			onInput(null);
16
			commentField.wordWrap = true;
17
			area.wordWrap = true;
18
		}

Step 10: The onInput Function

The onInput function will update the text field at the bottom of our application. It simply takes the amount of characters entered into the comment form and subtracts the total amount allowed. We use both the "KEY_UP" and "KEY_DOWN" events because we want the field to update even when someone is holding a certain key down. Also we check to see if the comment text field is full. If it is, we turn the text red.

1
2
		private function onInput(event:KeyboardEvent):void
3
		{
4
			dyText.text = String(commentField.maxChars - commentField.length) + " characters left";
5
			if(dyText.text == "0 characters left")
6
			{
7
				dyText.textColor = 0xff0000;
8
			}
9
			else
10
			{
11
				dyText.textColor = 0x000000;
12
			}
13
		}

Step 11: Handling the Click

This is the function that will handle the "CLICK" event. Here is where we pass the variables over to PHP, and listen for the "COMPLETE" event. However, before we send anything over to PHP, we need to check and make sure that the text fields aren't empty. If they are, then we change their label text field to red.

1
2
private function onClick(event:MouseEvent):void
3
		{
4
			button.focusRect = false;
5
			stage.focus = button;
6
			var name:String = nameField.text;
7
			var email:String = emailField.text.toLowerCase();
8
			var comment:String = commentField.text;
9
			if(validateString(name))
10
			{
11
				if(validateEmail(email))
12
				{
13
					if(validateString(comment))
14
					{
15
						var url:URLLoader = new URLLoader();
16
						var req:URLRequest = new URLRequest(URL+"/leave.php");
17
						var vars:URLVariables = new URLVariables();
18
						req.method = URLRequestMethod.POST;
19
						vars.submit = true;
20
						vars.name = name;
21
						vars.email = email;
22
						vars.comment = comment;
23
						if(newsletter.selected)
24
						{
25
							vars.newsletter = true;
26
						}
27
						else
28
						{
29
							vars.newsletter = false;
30
						}
31
						req.data = vars;
32
						url.addEventListener(Event.COMPLETE, onComplete);
33
						url.addEventListener(IOErrorEvent.IO_ERROR, onError);
34
						url.load(req);
35
					}
36
					else
37
					{
38
						commentText.textColor = 0xff0000;
39
						tf = commentText;
40
					}
41
				}
42
				else
43
				{
44
					emailText.textColor = 0xff0000;
45
					tf = emailText;
46
				}
47
			}
48
			else
49
			{
50
				nameText.textColor = 0xff0000;
51
				tf = nameText;
52
			}
53
		}

Step 12: Validate the Text Fields

Here are the two functions used to validate our text fields. The validateEmail function takes the text field and runs a regular expression on it to verify the email. The validateString function will strip all the HTML tags that might be inserted and makes sure that there is at least text in that field.

1
2
private function validateEmail(string:String):Boolean
3
		{
4
			var pattern:RegExp = /[a-z0-9!#$%&"*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&"*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g;
5
			if(pattern.exec(string) != null)
6
			{
7
				return true;
8
			}
9
			else
10
			{
11
				return false;
12
			}
13
		}
14
		private function validateString(string:String):Boolean
15
		{
16
			var bool:Boolean;
17
			var pattern:RegExp = /<\/?\w+((\s+(\w|\w[\w-]*\w)(\s*=\s*(?:\".*?\"|".*?"|[^"\">\s]+))?)+\s*|\s*)\/?>/gi;
18
			string = string.replace(pattern, "");
19
			var pattern2:RegExp = /[a-zA-Z0-9]/g;
20
			if(string.search(pattern2) == -1)
21
			{
22
				bool = false;
23
			}
24
			else
25
			{
26
				bool = true;
27
			}
28
			return bool;
29
		}

Step 13: The SQL Code

Here is the sql code to create the table on your database.

1
2
 CREATE TABLE `YOUR_DATABASE`.`comments` (
3
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
4
`name` VARCHAR( 40 ) NOT NULL ,
5
`email` VARCHAR( 40 ) NOT NULL ,
6
`comment` VARCHAR( 1200 ) NOT NULL
7
) ENGINE = MYISAM

Step 14: The Database Connection

The first part of our PHP is to create our database connection. Copy this code into a new php file. Save the file as "require.php".

1
2
<?php
3
$username = "YOUR_USERNAME";
4
$password = "YOUR_PASSWORD";
5
$hostname = "YOUR_HOST"; 
6
7
$dbhandle = mysql_connect($hostname, $username, $password)
8
or die("Unable to connect to MySQL");
9
10
$selected = mysql_select_db("YOUR_DATABASE",$dbhandle)
11
or die("Could not select examples");
12
13
?>

Step 15: Inserting Comments into the Database

With the database file saved, we can then access it in our feedback form. The "require_once" line will load the database connection file. We have some added security this way. We then check to see if the "submit" variable is empty. We sent the "submit" from Flash when we clicked the button to send. If the variable isn't empty, we populate our variables on the PHP side. After we clean the values, we insert them into the database. Save this file as "leave.php" into the same directory as your "require.php" file.

1
2
<?php
3
require_once("require.php");
4
if(!empty($_POST["submit"]))
5
{
6
	$name = $_POST["name"];
7
	$email = $_POST["email"];
8
	$comment = $_POST["comment"];
9
	$newsletter = $_POST["newsletter"];
10
	$name = validateString($name);
11
	$email = validateString($email);
12
	$email = filter_var($email, FILTER_SANITIZE_EMAIL);
13
	$comment = validateString($comment);
14
	if($newsletter)
15
	{
16
		if(handleEmail($name, $email))
17
		{
18
			echo 1;
19
		}
20
		else
21
		{
22
			echo 0;
23
		}
24
	}
25
	$query = "INSERT INTO comments VALUES("","$name","$email", "$comment")";
26
	mysql_query($query) or die(mysql_error());
27
	echo 1;
28
	mysql_close($dbhandle);
29
}
30
else
31
{
32
	echo 0;
33
}
34
?>

Step 16: Cleaning the Values

Here is where we clean the values to insert into our database. We escape any dangerous inputs, then we strip all the html tags out of the value. Then, just in case something made it through, we sanitize the value.

1
2
function validateString($string)
3
{
4
	$string = mysql_real_escape_string($string);
5
    $string = strip_tags($string);
6
	$string = filter_var($string, FILTER_SANITIZE_STRING);
7
	return $string;
8
}

Step 17: Handling the Email

This is the function that we use to send the email out. For this example, I"m using "PHPMailer". You can download the source here. This is a very simple class to work with. Here we require the class like we did with our database connection. We tell PHPMailer that we're sending an HTML email, and pass it to and from values as well as the HTML string. You'll notice in the "AddAddress" method, we pass the email and name values. The final function is the HTML content. It can be adjusted to say whatever you want. This function is only called if the "newsletter" Checkbox is clicked.

1
2
function handleEmail($name, $email)
3
{
4
	require("phpMailer/class.phpmailer.php");
5
	$mail = new PHPMailer();
6
	$mail->From = "YOUR_FROM_ADDRESS(mail@example.com)";
7
	$mail->FromName = "YOUR_FROM NAME(webmaster)";
8
	$mail->AddReplyTo("YOUR_REPLY_TO_NAME(no-reply@example.com");
9
	$mail->AddAddress($email, $name);
10
	$mail->isHTML(true);
11
	$mail->Subject = "YOUR_SUBJECT";
12
	$mail->Body = emailContent($name);
13
	if(!$mail->Send()) {
14
	  return false;
15
	} else {
16
	  return true;
17
	}
18
}
19
20
function emailContent($name)
21
{
22
	$emailString = "<html>\n";
23
	$emailString .= "<head>\n";
24
	$emailString .= "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
25
	$emailString .= "<title>Test email</title>\n";
26
	$emailString .= "</head>\n";
27
	$emailString .= "<body>\n";
28
	$emailString .= "<table width=\"600\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n";
29
	$emailString .= "<tr>\n";
30
	$emailString .= "<td width=\"100%\" height=\"30\" bgcolor=\"#003366\" align=\"center\"><font face=\"Arial\" color=\"#FFFFFF\" style=\"font-size:15px; font-weight:bold;\">NEWSLETTER HEADER</font></td>\n";
31
	$emailString .= "</tr>\n";
32
	$emailString .= "<tr>\n";
33
	$emailString .= "<td width=\"90%\" align=\"left\" style=\"padding:15px;\"><font face=\"Arial\" style=\"font-size:12px;\"><b>Dear $name</b><br /><b>CONGRATULATIONS!</b> You have just been added to our email community...but not really.</font></td>\n";
34
	$emailString .= "</tr>\n";
35
	$emailString .= "<tr>\n";
36
	$emailString .= "<td width=\"100%\" height=\"30\" bgcolor=\"#003366\" align=\"center\"><font face=\"Arial\" color=\"#FFFFFF\" style=\"font-size:15px; font-weight:bold;\">NEWSLETTER FOOTER</font></td>\n";
37
	$emailString .= "</tr>\n";
38
	$emailString .= "</table>\n";
39
	$emailString .= "</body>\n";
40
	$emailString .= "</html>";
41
	return $emailString;
42
}

Step 18: Retrieving the Comments

Open another blank PHP file. Save this one as "comments.php". Here we use our "require.php" file again, then we perform a simple MySQL query. It selects all the values from the database. We take all the values returned and echo out the XML. First we'll send the header, then echo out the beginning parts of the XML. After that, we go into a while loop. This will part will echo out all of our comments, email addresses, and names. When the while loop is over, we close the XML. This is what we will be loading back into Flash.

1
2
<?php
3
require_once("require.php");
4
$result = mysql_query("SELECT * FROM `comments`");
5
if($result)
6
{
7
	header ("Content-Type: text/xml");
8
	echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
9
	echo "<comments\n>";
10
	while ($row = mysql_fetch_array($result))
11
	{
12
		echo "<comment\n>";
13
		echo "<name>" . $row["name"] . "</name>\n";
14
		echo "<email>" . $row["email"] . "</email>\n";
15
		echo "<description>" . $row["comment"] . "</description>\n";
16
		echo "</comment\n>";
17
	}
18
	echo "</comments>";
19
}
20
?>

Step 19: Back in Flash

Here is the function that loads after the PHP has inserted our comments into the database. We set all the text fields back to their default states. Then we load the XML from the "comments.php" file.

1
2
private function onComplete(event:Event):void
3
		{
4
			if(event != null)
5
			{
6
				nameField.text = "";
7
				emailField.text = "";
8
				commentField.text = "";
9
				onInput(null);
10
				newsletter.selected = false;
11
			}
12
			var url:URLLoader = new URLLoader();
13
			url.addEventListener(Event.COMPLETE, xmlLoaded);
14
			url.addEventListener(IOErrorEvent.IO_ERROR, onError);
15
			url.load(new URLRequest(URL+"/comments.php"));
16
		}

Step 20: Parse the XML

This is the function for when the XML is loaded. We take the XML from the database, sort through it in a loop, then add the objects to the list component. We then set the focus of the list to the last item in the loop, which is the last comment.

1
2
private function xmlLoaded(event:Event):void
3
		{
4
			list.removeAll();
5
			var xml:XML = new XML(event.target.data);
6
			var listing:XMLList = xml..comment;
7
			var len:int = listing.length();
8
			for(var i:int; i<len; i++)
9
			{
10
				var object:Object = listing[i];
11
				list.addItem({label:object.name, data:object});
12
			}
13
			list.addEventListener(Event.CHANGE, onChange);
14
			list.selectedIndex = len-1;
15
			area.htmlText = listing[len-1].description;
16
			list.scrollToIndex(len-1);
17
		}

Step 21: Finishing up

Finally, we get to the rest of the functions to make the application work correctly. Just in case there's a server error, we listen for the "IOErrorEvent". If the server is down, Flash will call a javascript alert using the "ExternalInterface" class. The "onChange" function is called everytime the user selects a different list item. It sets the text field below the list to the corresponding comment. The "onFocus" function simply turns the text field assigned to the "tf" variables back to black.

1
2
private function onError(event:IOErrorEvent)
3
		{
4
			ExternalInterface.call("alert", "Server is unavailable");
5
		}
6
		private function onChange(event:Event):void
7
		{
8
			var object:Object = event.target.selectedItem.data;
9
			area.htmlText = object.description;
10
		}
11
        private function onFocus(event:FocusEvent):void
12
		{
13
			if(tf != null)
14
			{
15
				tf.textColor = 0x000000;
16
			}
17
		}

Conclusion

There are many different ways to make Flash, PHP, and MySQL work together. Once you get the hang of it, there's no limit to what you can do. The Tuts+ sites have a plethora of useful information out there, so don't forget to sign up for every one of their feeds. Thanks!

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.