A simple PHP mail contact form with MySQL

by Fausto Carrera 42

Welcome to the first PHP tutorial on TheTechLabs.com. In this tutorial I’m gonna show you how to make a simple php contact form for any website, sending the info by mail and saving it on a MySQL DataBase. This tutorial will be like an intro to a more detailed and complex series of php articles that in the end will result on the interaction of php and flash in a cms system. 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
  • Download the source files

Pre-Requesites

  • Basic PHP knowledge
  • HTML forms knowledge

Database structure

Our first step it’s define our Data Base structure. In this case in particular we gonna have fields from the data entered by the user and automatic server data, as the ip address, so we could track some additional info of the user. So our database must looks something like

  • id
  • name
  • email
  • url
  • comment
  • date
  • ip

Create the Database

For this step we could use the phpMyAdmin interface to create the data base or use the SQL file provided in the tutorial

  • id – integer with size 11 and auto increment used as index of the table
  • name – Varchar with 100 chars, it can’t be null
  • email – Varchar with 100 chars, it can’t be null
  • url – Varchar with 200 chars
  • comment – Text
  • date – DateTime
  • ip – – Varchar with 255 chars

Or just run the script on the phpMyAdmin SQL section:

CREATE TABLE IF NOT EXISTS `contacts` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `url` varchar(200) default NULL,
  `comment` text,
  `date` datetime NOT NULL,
  `ip` varchar(255),
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

The form

Our form gonna have 3 input fields and 1 text area:

  • Name
  • Email
  • Website url
  • Comment

So, now we could start with the form. The action gonna pass the data to itself via POST, so we gonna need and additional hidden field called action, so when the data it’s submitted, we check that variable to know if something it’s sent and act accordingly.

<form id="contact" name="contact" action="contact.php" method="post">

<p><label>Name: <input type="text" id="name" name="name" value="" /></label></p>

<p><label>Email: <input type="text" id="email" name="email" value="" /></label></p>

<p><label>Website: <input type="text" id="url" name="url" value="http://" /></label></p>

<p><label>Comment:<br /><textarea id="comment" name="comment"></textarea></label></p>

<input type="hidden" id="action" name="action" value="submitform" />

<p><input type="submit" id="submit" name="submit" value="Submit" /> <input type="reset" id="reset" name="reset" value="Reset" /></p>

</form>

Now our form must looks something like this one:

Notice the hidden input with the action id, it have the submitform value, this gonna help us to determine if we save the data or not

The data base connection

Now we have to define a data base connection before we could save the data, we gonna need the login, the password and the name of the database. So, in a new file called connection.php we define the new connection, this is because we probably gonna re use the connection in other pages, it’s better define it in a file we could include later in any php page.

$hostname = "localhost";
$database = "db_contacts";
$username = "root";
$password = "back2skl";
$connection = mysql_connect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR);

The additional functions

When we work with databases, it’s quite possible we have serious security problems. One of the most common attacks it’s the SQL injection, one way to avoid SQL injections is sanitize the data we enter on a form, this function cast the different values we enter and return teh right type, so if someone enter a SQL command to delete the data on the database, the command gonna be stored as text and don’t gonna execute

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;
}

Notice that we use the PHP function add slashes before we enter to the switch, in this way we have a string with backslashes before characters that need to be quoted in database queries, the we enter ans set the type of data we need according to the type

Recieving the data

Now we include the connection file and check if there’s something to save and send by mail, all at the beginning of the contact file.

//include the connection file

require_once('connection.php');

//save the data on the DB and send the email

if(isset($_POST['action']) && $_POST['action'] == 'submitform')
{
	//recieve the variables

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

We use another PHP function to get the ip of the visitor using the gethostbyname($_SERVER[‘REMOTE_ADDR’])

Saving data

So, by now we received the data from our form, now we gonna save the data on our data base

//save the data on the DB

mysql_select_db($database, $connection);

$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 = mysql_query($insert_query, $connection) or die(mysql_error());

So, we select our data base, then we make the query and put it on a variable to make the mysql_query or stop if somethings go wrong. Notice two things, first we are using the MySQL NOW(); function for the dateTime field and we are sanitizing each variable we enter on the data base.

Sending email

So, if everything goes fine, we gonna have something like this in our phpMyAdmin

Now we could send an email to the interested person, like the webmaster, about the new comment on the website

if($result)
{
	//send the email

	$to = "[email protected]";
	$subject = "New contact from the website";

	//headers and subject
	$headers  = "MIME-Version: 1.0rn";
	$headers .= "Content-type: text/html; charset=iso-8859-1rn";
	$headers .= "From: ".$name." <".$email.">rn";

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

	mail($to, $subject, $body, $headers);

	//ok message

	echo "Your message has been sent";
}

First we check if php insert the data on the data base, then we set who receives and the subject of the email, then we set the headers of the email, so it could be delivered as html, and finally we compose the email. all the code must looks something like this

//include the connection file

require_once('connection.php');

//save the data on the DB and send the email

if(isset($_POST['action']) && $_POST['action'] == 'submitform')
{
	//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

	mysql_select_db($database, $connection);

	$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 = mysql_query($insert_query, $connection) or die(mysql_error());

	if($result)
	{
		//send the email

		$to = "[email protected]";
		$subject = "New contact from the website";

		//headers and subject
		$headers  = "MIME-Version: 1.0rn";
		$headers .= "Content-type: text/html; charset=iso-8859-1rn";
		$headers .= "From: ".$name." <".$email.">rn";

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

		mail($to, $subject, $body, $headers);

		//ok message

		echo "Your message has been sent";
	}
}

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;
}

Well, that’s all, now you could make your own PHP forms, knowing how to add or remove fields, remember to do the same with the data base. Hope you find this tutorial usefull, and thanks for read.

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>