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
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:
- The constructor where we set the hostname, the username, the password and the database we gonna use
- The query function to make the quries to the data base
- 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:
- Pass a query as a variable
- Connect to the MySQL server
- Connect to the data base
- Make a query
- 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
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 = "noreply@domain.com";
$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("your@email.com", "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 = "noreply@domain.com";
$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("your@email.com", "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.


April 27th, 2009 at 2:15 am
Awesome piece! This is nice if one just wants a quick setup, and does not need to use AMFPHP or ZendAMF. Nice work.
June 3rd, 2009 at 9:24 am
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?
June 5th, 2009 at 9:21 am
Thanks, nice simple and concise ActionScript.
July 12th, 2009 at 10:42 am
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.
July 24th, 2009 at 3:33 pm
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 ?
August 8th, 2009 at 12:01 pm
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!!!
August 8th, 2009 at 4:16 pm
The flash/php doesn’t work.
August 9th, 2009 at 9:48 pm
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.
November 16th, 2009 at 11:19 pm
Carefully selecting your words and strategically placing them on a page to create impulsive reactions from the reader can lead to a direct sell.
November 30th, 2009 at 10:59 pm
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.
December 29th, 2009 at 2:01 pm
Why isn’t this working for me?!
January 4th, 2010 at 5:37 am
Nice review. Enjoying it very much!
January 19th, 2010 at 1:26 pm
This site must have taken you a while to put together, found it by searching for “free stuff” and its ace!! Congrats x
January 31st, 2010 at 12:46 am
I look forward to reading your posts. Thanks for all the work!
January 31st, 2010 at 11:11 pm
I usually don
February 15th, 2010 at 9:22 am
Thank you for sharing.
February 19th, 2010 at 9:30 pm
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.
February 21st, 2010 at 8:09 pm
really nice. im going to copy this to my website, really looks good
February 22nd, 2010 at 7:42 pm
Participating in searching pro sites connected to mesh hosting and specifically comparison hosting linux graph mesh, your place came up.
March 1st, 2010 at 6:54 pm
Great articles & Nice a site
March 3rd, 2010 at 12:32 am
I was taking a break from homework and started reading…and couldnt stop
March 4th, 2010 at 12:51 pm
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
March 10th, 2010 at 9:19 pm
Hope everything is well, thanks for this great price. I”m a daily reader and just wanted to say thank you so much!
March 20th, 2010 at 11:29 pm
Excellent blog, i will keep visiting this blog very often.
March 24th, 2010 at 1:15 am
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?
March 24th, 2010 at 2:08 pm
Excellent post. I have read many blog posts, but they usually don’t give away the level of quality information that your blog do.
April 3rd, 2010 at 3:30 pm
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.
April 13th, 2010 at 5:55 pm
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!
April 22nd, 2010 at 2:06 pm
Nice review. Thank you for sharing
May 9th, 2010 at 5:42 am
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 !
May 17th, 2010 at 12:02 pm
asking yourself wonderful
May 29th, 2010 at 9:28 am
I haven’t seen this done in such as succint way….Nice