How to create a simple Flash/PHP mail contact form with Actionscript 3.0 and MySQL

by Fausto Carrera 83 views38

Welcome to the second PHP tutorial on TheTechLabs.com. In this tutorial I’m gonna show you how to improve our simple php, sending the info by mail and saving it on a MySQL DataBase using a custom MySQL class that we could reuse anytime and phpMailer, an open source class to send mails. And, of course, we gonna use a flash form to send the form instead of the html form. Hope you enjoy the tutorial.

Requirements

  • A text editor to edit php, it’s not necessary a professional editor, with NotePad or NotePad++ it’s ok
  • A PC with XAMPP or other web server with PHP support installed, or access to a PHP web server
  • Access to the phpMyAdmin
  • Access to a MySQL data base
  • Flash Contact Form Source Files

This is the demo of the form we are going to build.

Pre-Requesites

  • Basic PHP knowledge

Folders structure

It’s a good idea have an order with the different folders, this will help us when our application grows. For this tutorial we gonna have a structure like this:

Fig.01-Structure
Fig.01-Structure

My main folder contains the index.php that holds the SWF file, the contact.php, that connect to the data base through the mysql class, save the data and send the email, and a folder called classes where I save all the classes used to save the data and send the email.

The MySQL class

We gonna work with our previous MySQL data base structure.

PHP5 brings some substantial improvements comparing to the PHP4 OOP implementation, so it’s easier to work OOP in PHP now.

So, basically our MySQL class have 3 parts:

  1. The constructor where we set the hostname, the username, the password and the database we gonna use
  2. The query function to make the quries to the data base
  3. Additional functions to work with the query, like return the number of rows, display the result as object, array or an associate matrix

If you have a lil bit knowledge about OOP in Flash, it’s the same way in PHP. The Class is a collection of methods that helps us to achieve objectives, and we could reuse it anytime we want and apply it in different places, not only in our project but in different projects, and we have the same kind of fields as in ActionScript, public and private, and objects are created in the same way with the new keyword.

Create the class

So, our first step is create the class. First we create a new empty document in Notepad++, and we call it class.mysql.php, and we save it on the classes folder. In our class.mysql.php file we could create the class:

class Mysql{
}

And that’s it, we created our first php class, pretty easy right.

Define the variables

So, we have to declare the variables to connect to the data base, and we have:

  • The Host, 99% of the time is localhost
  • The mysql user name to connect to the mysql server and data base
  • The user password to connect to the mysql server and data base
  • The name of the data base

We declare all this variables as private, so they could be accessed just inside the class.

private $host;			//the server host 90% of being localhost
private $user;			//the username
private $password;		//the password
private $db;			//the database to select

The constructor

In our construct function, the one who initialize our class, we put the data about the server, the username, the password and the data base and set it to our previous variables

function __construct(){
	$this->host = "localhost";
	$this->user = "username";
	$this->password = "password";
	$this->db = "database";
}

The query function

So, by now we have set the necessary data to connect with the data base, now we create the query function that gonna lets us make queries to the data base.

With this function we gonna:

  1. Pass a query as a variable
  2. Connect to the MySQL server
  3. Connect to the data base
  4. Make a query
  5. return a result to insert datra or handle it later to display data
function query($sql_query){
	//we try to connect to the mysql server
	$link = @mysql_connect($this->host, $this->user, $this->password);
	//if the connection failed, we stop the application and return an error
	if(!$link) die("Could not connect to the MySQL server: " . @mysql_error());
	//we try to connect with the database
	$sel_db = @mysql_select_db($this->db, $link);
	//if fail, we stop the application and return an error
	if(!$sel_db) die("Could not connect to the data base: " . @mysql_error());
	//if everything goes fine till here, we make the query
	$query = @mysql_query($sql_query, $link);
	//if the query fail, we return an error
	if(!$query) die("Error: " . @mysql_error());
	//we colse the mysql connection
	@mysql_close($link);
	//now we return the result
	return $query;
}

The number of rows

A useful data when we work with databases it’s the number of rows. This number gives us the total number of results returned from a query, pretty useful for pagination and other stuff.

function numRows($result)
{
	$num_rows = @mysql_num_rows($result);
	return $num_rows;
}

Notice that we pass the result from a query, not a query.

The result as an object

We have different ways to retrieve the information, I’m gonna explain 3 basics, the first is have the result as an object:

function fetchObject($result)
{
	$row = @mysql_fetch_object($result);
	return $row;
}

and we retrieve the data as $row->field_name;

The result as an enumerated array

We could retrieve the data as an enumerated array too:

function fetchRow($result)
{
	$row = @mysql_fetch_row($result);
	return $row;
}

and we retrieve the data as $row[0], $row[1] and so on.

The result as an enumerated array and/or an associative array

function fetchArray($result)
{
	$row = @mysql_fetch_array($result);
	return $row;
}

and we retrieve the data as $row[0] or $row[‘field_name’], both are valid.

The result as an associative array

function fetchAssoc($result)
{
	$row = @mysql_fetch_assoc($result);
	return $row;
}

and we retrieve the data as $row[‘field_name’].

I really prefer the object approach, but the 3 are valid, and you have the 3 options, some prefer the Associative array approach other the Array approach, all depends on what make you feel more comfortable.

Test our class

So, if everything goes fine till now, we could make a little php file to test our class before program the html form. For this example we must have some data on our database, we could insert some test data from the phpmyadmin

We create a test.php file and save it on our folder. We gonna make a query to retrieve all the data from our table contacts and show the name, and the comment of each row.

First we include our mysql class

//we include the mysql class
require_once('classes/class.mysql.php');
//we start the mysql class
$connection = new Mysql();
//make the query
$query = "SELECT * FROM contacts ORDER BY id ASC";
//pass the query to the new mysql class object
$result = $connection->query($query);
//retrieve the total items
$total_items = $connection->numRows($result);
//print the total number on screen
echo "Total contacts: ".$total_items;

Now we could use a while loop to print the data on screen

while($row_contact = $connection->fetchAssoc($result)){
echo "

Name:".$row_contact['name']."
";
echo "Comment:".$row_contact['comment']."

";
echo "

";

If we point our browser to the test.php file we gonna have something like this

Fig.02-Test Screen
Fig.02-Test Screen

Implementing our class in the HTML contact form

With the contact form from our last tutorial, we make little changes to make it work with our new mysql class:

//include the mysql class and the phpmailer class
require_once('classes/class.mysql.php');
require_once('classes/class.phpmailer.php');

if(isset($_POST['action']) && $_POST['action'] == 'submitform')
{
	//new mysql object

	$connection = new Mysql;

	//recieve the variables

	$name = $_POST['name'];
	$email = $_POST['email'];
	$url = $_POST['url'];
	$comment = $_POST['comment'];
	$ip = gethostbyname($_SERVER['REMOTE_ADDR']);

	//save the data on the DB

	$insert_query = sprintf("INSERT INTO contacts (name, email, url, comment, date, ip) VALUES (%s, %s, %s, %s, NOW(), %s)",
							sanitize($name, "text"),
							sanitize($email, "text"),
							sanitize($url, "text"),
							sanitize($comment, "text"),
							sanitize($ip, "text"));

	$result = $connection->query($insert_query);

	if($result)
	{
		//send the email

		$mail = new PHPMailer();
		$mail->IsSMTP(); // telling the class to use SMTP
		$mail->Host = "smtp.domain.com"; // SMTP server
		$mail->From = "[email protected]";
		$mail->FromName = "Website";
		$mail->Subject = "New contact from the website";

		//message body

		$body = "New contact
";
		$body .= "Name: ".$name."
";
		$body .= "Email: ".$email."
";
		$body .= "Comment: ".$comment."
";
		$body .= "IP: ".$ip."
";

		$mail->MsgHTML($body);
		$mail->AddAddress("[email protected]", "your name");

		if(!$mail->Send()) {
		  echo "An error has occurred";
		} else {
		  echo "Your message has been sent";
		}
	}
}

It looks the same, but with the difference that we implement our mysql class and the php mailer class to send the email.

The Flash contact form

Now, we could make our flash form. For this we gonna use URLRequest, URLVariables and URLLoader to send the data via post.

So we start making 4 input fields called:

  • name_txt
  • email_txt
  • website_txt
  • comment_txt

and the send button, called send_btn

So, now we could set everything on flash to send our comments and stored on our data base.

import flash.events.Event;
import flash.net.*;

stop();

var contact_url:String = "contact.php"; //the name of our php file to contact the data base
var contactRequest:URLRequest = new URLRequest(contact_url);
var contactLoader:URLLoader = new URLLoader();
var contactVariables:URLVariables = new URLVariables();

send_btn.addEventListener(MouseEvent.CLICK, sendForm);

function sendForm(evt:MouseEvent):void
{
	// add the variables to our URLVariables
	contactVariables.action = "submitform";
	contactVariables.name = name_txt.text;
	contactVariables.email = email_txt.text;
	contactVariables.url = website_txt.text;
	contactVariables.comment = comment_txt.text;
	// send data via post
	contactRequest.method = URLRequestMethod.POST;
	contactRequest.data = contactVariables;
	// add listener
	contactLoader.addEventListener(Event.COMPLETE, onLoaded);
	contactLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
	//send data
	contactLoader.load(contactRequest);
	//show sending message
	trace("sending");
}

function onLoaded(evt:Event):void
{
	var result_data:String = String(contactLoader.data);
	if (result_data == "ok")
	{
		trace("sended");
	}
	else if (result_data == "error")
	{
		trace("error");
	}
}

function ioErrorHandler(event:IOErrorEvent):void
{
	trace("ioErrorHandler: " + event);
}

And in our php file contact.php it’s the same as contact_form.php but without the html header and the form:

require_once('classes/class.mysql.php');
require_once('classes/class.phpmailer.php');

if(isset($_POST['action']) && $_POST['action'] == 'submitform')
{
	//new mysql

	$connection = new Mysql;

	//recieve the variables

	$name = $_POST['name'];
	$email = $_POST['email'];
	$url = $_POST['url'];
	$comment = $_POST['comment'];
	$ip = gethostbyname($_SERVER['REMOTE_ADDR']);

	//save the data on the DB

	$insert_query = sprintf("INSERT INTO contacts (name, email, url, comment, date, ip) VALUES (%s, %s, %s, %s, NOW(), %s)",
							sanitize($name, "text"),
							sanitize($email, "text"),
							sanitize($url, "text"),
							sanitize($comment, "text"),
							sanitize($ip, "text"));

	$result = $connection->query($insert_query);

	if($result)
	{
		//send the email

		$mail = new PHPMailer();
		$mail->IsSMTP(); // telling the class to use SMTP
		$mail->Host = "smtp.domain.com"; // SMTP server
		$mail->From = "[email protected]";
		$mail->FromName = "Website";
		$mail->Subject = "New contact from the website";

		//message body

		$body = "New contact
";
		$body .= "Name: ".$name."
";
		$body .= "Email: ".$email."
";
		$body .= "Comment: ".$comment."
";
		$body .= "IP: ".$ip."
";

		$mail->MsgHTML($body);
		$mail->AddAddress("[email protected]", "your name");

		if(!$mail->Send()) {
		  echo "error";
		} else {
		  echo "ok";
		}
	}
}

function sanitize($value, $type)
{
  $value = (!get_magic_quotes_gpc()) ? addslashes($value) : $value;

  switch ($type) {
    case "text":
      $value = ($value != "") ? "'" . $value . "'" : "NULL";
      break;
    case "long":
    case "int":
      $value = ($value != "") ? intval($value) : "NULL";
      break;
    case "double":
      $value = ($value != "") ? "'" . doubleval($value) . "'" : "NULL";
      break;
    case "date":
      $value = ($value != "") ? "'" . $value . "'" : "NULL";
      break;
  }

  return $value;
}

Before test it, don’t forget to change the data used in the phpmailer so you could ber able to send email. For more information on the phpmailer, don’t forget to read the examples and tutorials

You could test your php code without flash using the same form in an html file and making the action=”contact.php”, so you could debug it.

Comments (38)

  1. Awesome piece! This is nice if one just wants a quick setup, and does not need to use AMFPHP or ZendAMF. Nice work.

  2. hmm, i don’t think this solution works. Even the example on this page freezes on ‘sending message..’. the same with me. the php form works great, adding new entries to mysql database and sending e-mail.

    but the communication between flash and the php form doesn’t work.

    anyone else having trouble with this?

  3. Thanks, nice simple and concise ActionScript.

  4. I found your blog by chance . but i have to say that it’s great blog very useful information and very interesting subjects just greetings and good luck
    i’m not going i will be always checking for updates.I’m very interested in CMS and all its related subjects.

  5. So the php works fine alone, but when it is with flash, it blocks on the require_once. is something in php.ini to do that the require_once works when flash call the php ?

  6. Great having this, but you have to be very precise when it comes to teaching us. I am saying this because when one start with you at the beginning, one is expecting you mention everything in details, just like you building it yourself, this tutorial is not clear to me, yes sending from this flash freezes, please do something about it, I will come back for update.

    Thank you
    Please make it clearer, please!!!

  7. The flash/php doesn’t work.

  8. yes the flash/php doesn’t work. I’m not the only one who followed the tutorial then 😛

    My workaround was not using the mysql at all. I used phpmailer only to send me feedback straight to my mail. you can check my website to see how it works. I can send you the code if you contact me.

  9. Carefully selecting your words and strategically placing them on a page to create impulsive reactions from the reader can lead to a direct sell.

  10. FOR THOSE HAVING PROBLEMS:

    For some reason, when php echo’s back the data to flash, it will include white space that exists outside the tags. When this happens, the data returned will not equal ‘ok’ or ‘error’. To avoid this, make sure the php file does not have any white space outside the php tags, or filter any white space at the beginning or end of the returned data.

    ——For example, replace:
    var result_data:String = String(contactLoader.data);

    ——with:
    var result_data:String = String(contactLoader.data).replace(/^\s+/, “”).replace(/\s+$/, “”);

    Then the correct data will be returned to flash making the application show the final results correctly.

  11. Why isn’t this working for me?!

  12. Nice review. Enjoying it very much!

  13. This site must have taken you a while to put together, found it by searching for “free stuff” and its ace!! Congrats x

  14. I look forward to reading your posts. Thanks for all the work!

  15. Very Nice Read! Looking forward to more on this subject Bookmarked the blog. Was just curious if anybody could point me to some related material. Thanks in advance.

  16. really nice. im going to copy this to my website, really looks good

  17. Participating in searching pro sites connected to mesh hosting and specifically comparison hosting linux graph mesh, your place came up.

  18. I was taking a break from homework and started reading…and couldnt stop

  19. Thank you for discussing such an informative article with all of us. I’ve bookmarked your blog will come back for a re-read again. Keep up the great work. We have a Dan Kennedy Copywriting seminar that we offer to our customers you can check it out here Copywriting Courses Visit This

  20. Hope everything is well, thanks for this great price. I”m a daily reader and just wanted to say thank you so much!

  21. Excellent blog, i will keep visiting this blog very often.

  22. Well, thanks a lot for the great work but the problem is that u neglect some details So beginners as myself kinda get lost,

    I’ve done your instructions step by step but still, can’t contact my database and the test doesn’t work although I am sure I typed the right info in the host name & the other fields.

    Maybe some 1 have a clue of what’s going on?

  23. Excellent post. I have read many blog posts, but they usually don’t give away the level of quality information that your blog do.

  24. Well, this is the second time, am commenting on this post, I don’t want to use the term “Amature in Mysql” but I guess you don’t know much about it, because you failed to mention or create the database contact, you neither created the table for which the contact information will be stored. Sorry back to school. you lack Mysql knowledge.

  25. Great post, I just making an email contact form because I have not much of PHP experience, I guess I can make a contact form and save message to database based your post, thanks!

  26. Hey there, I was just browing the web and came across your website . Thought I’d say hi and tell you that I’ve enjoyed my stay here, hope you have a lovely evening !

  27. I haven’t seen this done in such as succint way….Nice

  28. Nice article about creating a flashphp mail contact form. thanks for sharing

  29. thanks for the piece of code. it will really be helpful

  30. I think this is one of the best site for me.

  31. Great post! I’d like to see something that’s pretty simple and easy to understand at a glance, but with a lot of motion and activity to reflect the vibrancy of the community. Can’t wait to see what you and morgamic come up with.

  32. Hey this is good one!
    Can you even show us how can we display data from database in flash?
    Thanks!

  33. this website is very usefull thank you guys for putting up your efforts http://www.goamonitor.com
    .adslot-overlay {position: absolute; font-family: arial, sans-serif; background-color: rgba(0,0,0,0.65); border: 2px solid rgba(0,0,0,0.65); color: white !important; margin: 0; z-index: 2147483647; text-decoration: none; box-sizing: border-box; text-align: left;}.adslot-overlay-iframed {top: 0; left: 0; right: 0; bottom: 0;}.slotname {position: absolute; top: 0; left: 0; right: 0; font-size: 13px; font-weight: bold; padding: 3px 0 3px 6px; vertical-align: middle; background-color: rgba(0,0,0,0.45); text-overflow: ellipsis; white-space: nowrap; overflow: hidden;}.slotname span {text-align: left; text-decoration: none; text-transform: capitalize;}.revenue {position: absolute; bottom: 0; left: 0; right: 0; font-size: 11px; padding: 3px 0 3px 6px; vertial-align: middle; text-align: left; background-color: rgba(0,0,0,0.45); font-weight: bold; text-overflow: ellipsis; overflow: hidden; white-space: nowrap;}.revenue .name {color: #ccc;}.revenue .horizontal .metric {display: inline-block; padding-right: 1.5em;}.revenue .horizontal .name {padding-right: 0.5em;}.revenue .vertical .metric {display: block; line-height: 1.5em; margin-bottom: 0.5em;}.revenue .vertical .name, .revenue .vertical .value {display: block;}.revenue .square .metric, .revenue .button .metric {display: table-row;}.revenue .square .metric {line-height: 1.5em;}.revenue .square .name, .revenue .square .value, .revenue .button .value {display: table-cell;}.revenue .square .name {padding-right: 1.5em;}.revenue .button .name {display: block; margin-right: 0.5em; width: 1em; overflow: hidden; text-overflow: clip;}.revenue .button .name:first-letter {margin-right: 1.5em;}a.adslot-overlay:hover {border: 2px solid rgba(58,106,173,0.9);}a.adslot-overlay:hover .slotname {border-bottom: 1px solid rgba(81,132,210,0.9); background-color: rgba(58,106,173,0.9);}a.adslot-overlay:hover .revenue {border-top: 1px solid rgba(81,132,210,0.9); background-color: rgba(58,106,173,0.9);}div.adslot-overlay:hover {cursor: not-allowed; border: 2px solid rgba(64,64,64,0.9);}div.adslot-overlay:hover .slotname {border-bottom: 1px solid rgba(128,128,128,0.9); background-color: rgba(64,64,64,0.9);}div.adslot-overlay:hover .revenue {border-top: 1px solid rgba(128,128,128,0.9); background-color: rgba(64,64,64,0.9);}

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>