Sie sind auf Seite 1von 13

Create a Comment Form with Flash, PHP, XML and MySQL | Activetuts+ http://active.tutsplus.com/tutorials/actionscript/create-a-comment-form-wi...

Nov 13th in ActionScript, Intermediate by Jeremy Green

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!

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".

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.

1 of 13 1/3/2010 4:35 AM
Create a Comment Form with Flash, PHP, XML and MySQL | Activetuts+ http://active.tutsplus.com/tutorials/actionscript/create-a-comment-form-wi...

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.

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".

2 of 13 1/3/2010 4:35 AM
Create a Comment Form with Flash, PHP, XML and MySQL | Activetuts+ http://active.tutsplus.com/tutorials/actionscript/create-a-comment-form-wi...

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".

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.

3 of 13 1/3/2010 4:35 AM
Create a Comment Form with Flash, PHP, XML and MySQL | Activetuts+ http://active.tutsplus.com/tutorials/actionscript/create-a-comment-form-wi...

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.

4 of 13 1/3/2010 4:35 AM
Create a Comment Form with Flash, PHP, XML and MySQL | Activetuts+ http://active.tutsplus.com/tutorials/actionscript/create-a-comment-form-wi...

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.

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

view plaincopy to clipboardprint?

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

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.

view plaincopy to clipboardprint?

1. package {
2.

5 of 13 1/3/2010 4:35 AM
Create a Comment Form with Flash, PHP, XML and MySQL | Activetuts+ http://active.tutsplus.com/tutorials/actionscript/create-a-comment-form-wi...

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

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.

view plaincopy to clipboardprint?

1. public function commentForm()


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

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.

6 of 13 1/3/2010 4:35 AM
Create a Comment Form with Flash, PHP, XML and MySQL | Activetuts+ http://active.tutsplus.com/tutorials/actionscript/create-a-comment-form-wi...

view plaincopy to clipboardprint?

1. private function onInput(event:KeyboardEvent):void


2. {
3. dyText.text = String(commentField.maxChars - commentField.length) + " characters left";
4. if(dyText.text == "0 characters left")
5. {
6. dyText.textColor = 0xff0000;
7. }
8. else
9. {
10. dyText.textColor = 0x000000;
11. }
12. }

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.

view plaincopy to clipboardprint?

1. private function onClick(event:MouseEvent):void


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

7 of 13 1/3/2010 4:35 AM
Create a Comment Form with Flash, PHP, XML and MySQL | Activetuts+ http://active.tutsplus.com/tutorials/actionscript/create-a-comment-form-wi...

40. }
41. else
42. {
43. emailText.textColor = 0xff0000;
44. tf = emailText;
45. }
46. }
47. else
48. {
49. nameText.textColor = 0xff0000;
50. tf = nameText;
51. }
52. }

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.

view plaincopy to clipboardprint?

1. private function validateEmail(string:String):Boolean


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

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

1. CREATE TABLE `YOUR_DATABASE`.`comments` (


2. `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
3. `name` VARCHAR( 40 ) NOT NULL ,
4. `email` VARCHAR( 40 ) NOT NULL ,

8 of 13 1/3/2010 4:35 AM
Create a Comment Form with Flash, PHP, XML and MySQL | Activetuts+ http://active.tutsplus.com/tutorials/actionscript/create-a-comment-form-wi...

5. `comment` VARCHAR( 1200 ) NOT NULL


6. ) ENGINE = MYISAM

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".

view plaincopy to clipboardprint?

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

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.

view plaincopy to clipboardprint?

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

9 of 13 1/3/2010 4:35 AM
Create a Comment Form with Flash, PHP, XML and MySQL | Activetuts+ http://active.tutsplus.com/tutorials/actionscript/create-a-comment-form-wi...

30. {
31. echo 0;
32. }
33. ?>

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.

view plaincopy to clipboardprint?

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

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.

view plaincopy to clipboardprint?

1. function handleEmail($name, $email)


2. {
3. require("phpMailer/class.phpmailer.php");
4. $mail = new PHPMailer();
5. $mail->From = "YOUR_FROM_ADDRESS(mail@example.com)";
6. $mail->FromName = "YOUR_FROM NAME(webmaster)";
7. $mail->AddReplyTo("YOUR_REPLY_TO_NAME(no-reply@example.com");
8. $mail->AddAddress($email, $name);
9. $mail->isHTML(true);
10. $mail->Subject = "YOUR_SUBJECT";
11. $mail->Body = emailContent($name);
12. if(!$mail->Send()) {
13. return false;
14. } else {
15. return true;
16. }
17. }
18.
19. function emailContent($name)
20. {
21. $emailString = "<html>\n";
22. $emailString .= "<head>\n";
23. $emailString .= "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
24. $emailString .= "<title>Test email</title>\n";
25. $emailString .= "</head>\n";
26. $emailString .= "<body>\n";
27. $emailString .= "<table width=\"600\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n";
28. $emailString .= "<tr>\n";
29. $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";

10 of 13 1/3/2010 4:35 AM
Create a Comment Form with Flash, PHP, XML and MySQL | Activetuts+ http://active.tutsplus.com/tutorials/actionscript/create-a-comment-form-wi...

30. $emailString .= "</tr>\n";


31. $emailString .= "<tr>\n";
32. $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";
33. $emailString .= "</tr>\n";
34. $emailString .= "<tr>\n";
35. $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";
36. $emailString .= "</tr>\n";
37. $emailString .= "</table>\n";
38. $emailString .= "</body>\n";
39. $emailString .= "</html>";
40. return $emailString;
41. }

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.

view plaincopy to clipboardprint?

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

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.

view plaincopy to clipboardprint?

1. private function onComplete(event:Event):void


2. {
3. if(event != null)
4. {
5. nameField.text = "";
6. emailField.text = "";
7. commentField.text = "";
8. onInput(null);

11 of 13 1/3/2010 4:35 AM
Create a Comment Form with Flash, PHP, XML and MySQL | Activetuts+ http://active.tutsplus.com/tutorials/actionscript/create-a-comment-form-wi...

9. newsletter.selected = false;
10. }
11. var url:URLLoader = new URLLoader();
12. url.addEventListener(Event.COMPLETE, xmlLoaded);
13. url.addEventListener(IOErrorEvent.IO_ERROR, onError);
14. url.load(new URLRequest(URL+"/comments.php"));
15. }

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.

view plaincopy to clipboardprint?

1. private function xmlLoaded(event:Event):void


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

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.

view plaincopy to clipboardprint?

1. private function onError(event:IOErrorEvent)


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

12 of 13 1/3/2010 4:35 AM
Create a Comment Form with Flash, PHP, XML and MySQL | Activetuts+ http://active.tutsplus.com/tutorials/actionscript/create-a-comment-form-wi...

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!

13 of 13 1/3/2010 4:35 AM

Das könnte Ihnen auch gefallen