Setting up a database to handle form data from a website

PHP is a great scripting language that allows many dynamic functions in your site. You can create custom forms, form validation, and email responses using PHP. This article will explain the basics in creating an email form that validates the inputs, produces errors when inputs are typed incorrectly, and send an email to you when submitted.

This section of the code will validate the form inputs

Below is the code you will use to validate whether the inputs have valid data or not. This can be customized for different form field validations.

Note! You can paste the entire code directly in the body section of your webpage to get it working.

if (isset($_REQUEST['submitted'])) {
// Initialize error array.
$errors = array();
// Check for a proper First name
if (!empty($_REQUEST['firstname'])) {
$firstname = $_REQUEST['firstname'];
$pattern = "/^[a-zA-Z0-9\_]{2,20}/";// This is a regular expression that checks if the name is valid characters
if (preg_match($pattern,$firstname)){ $firstname = $_REQUEST['firstname'];}
else{ $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';}
} else {$errors[] = 'You forgot to enter your First Name.';}

// Check for a proper Last name
if (!empty($_REQUEST['lastname'])) {
$lastname = $_REQUEST['lastname'];
$pattern = "/^[a-zA-Z0-9\_]{2,20}/";// This is a regular expression that checks if the name is valid characters
if (preg_match($pattern,$lastname)){ $lastname = $_REQUEST['lastname'];}
else{ $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';}
} else {$errors[] = 'You forgot to enter your Last Name.';}

//Check for a valid phone number
if (!empty($_REQUEST['phone'])) {
$phone = $_REQUEST['phone'];
$pattern = "/^[0-9\_]{7,20}/";
if (preg_match($pattern,$phone)){ $phone = $_REQUEST['phone'];}
else{ $errors[] = 'Your Phone number can only be numbers.';}
} else {$errors[] = 'You forgot to enter your Phone number.';}

if (!empty($_REQUEST['redmapleacer']) || !empty($_REQUEST['chinesepistache']) || !empty($_REQUEST['raywoodash'])) {
$check1 = $_REQUEST['redmapleacer'];
if (empty($check1)){$check1 = 'Unchecked';}else{$check1 = 'Checked';}
$check2 = $_REQUEST['chinesepistache'];
if (empty($check2)){$check2 = 'Unchecked';}else{$check2 = 'Checked';}
$check3 = $_REQUEST['raywoodash'];
if (empty($check3)){$check3 = 'Unchecked';}else{$check3 = 'Checked';}
} else {$errors[] = 'You forgot to enter your Phone number.';}
//End of validation

Sends the email if validation passes

The following code is what sends the email. The inputs must pass the previous validation in order for the email to send. You will need to replace the "to" email address with the email address you want to receive the email to.

if (isset($_REQUEST['submitted'])) {
if (empty($errors)) {
$from = "From: Our Site!"; //Site name
// Change this to your email address you want to form sent to
$to = "";
$subject = "Admin - Our Site! Comment from " . $name . "";

$message = "Message from " . $firstname . " " . $lastname . "
Phone: " . $phone . "
Red Maple Acer: " . $check1 ."
Chinese Pistache: " . $check2 ."
Raywood Ash: " . $check3 ."";

Error Reporting Code

This code will print any errors that occurs such as an empty input.

//Print Errors
if (isset($_REQUEST['submitted'])) {
// Print any error messages.
if (!empty($errors)) {
echo '<hr /><h3>The following occurred:</h3><ul>';
// Print each error.
foreach ($errors as $msg) { echo '<li>'. $msg . '</li>';}
echo '</ul><h3>Your mail could not be sent due to input errors.</h3><hr />';}
else{echo '<hr /><h3 align="center">Your mail was sent. Thank you!</h3><hr /><p>Below is the message that you sent.</p>';
echo "Message from " . $firstname . " " . $lastname . " <br />Phone: ".$phone." <br />";
echo "<br />Red Maple Acer: " . $check3 . "";
echo "<br />Chinese Pistache: " . $check2 . "";
echo "<br />Raywood Ash: " . $check3 . "";
//End of errors array

Prints the contact form

This is the form that will display for the visitor to fill out.

  <h2>Contact us</h2>
<p>Fill out the form below.</p>
<form action="" method="post">
<label>First Name: <br />
<input name="firstname" type="text" value="- Enter First Name -" /><br /></label>
<label>Last Name: <br />
<input name="lastname" type="text" value="- Enter Last Name -" /><br /></label>
<label>Phone Number: <br />
<input name="phone" type="text" value="- Enter Phone Number -" /><br /></label>
<label>Red Maple Acer:
<input name="redmapleacer" type="checkbox" value="Red Maple Acer" /><br /></label>
<label>Chinese Pistache:
<input name="chinesepistache" type="checkbox" value="Chinese Pistache" /><br /></label>
<label>Raywood Ash:
<input name="raywoodash" type="checkbox" value="Raywood Ash" /><br /></label>
<input name="" type="reset" value="Reset Form" /><input name="submitted" type="submit" value="Submit" />

You can paste the entire code directly in the body section of your webpage to get it working. We have more tutorials with other methods to send email from your website at the following links.

Using phpMailer to Send Mail through PHP

How to set up FormMail

Continued Education in Course 205: Using PHP to create dynamic pages
You are viewing Section 1: How to create a custom PHP contact form with validation
Section 2: Setting up a database to handle form data from a website
Did you find this article helpful?

We value your feedback!

Why was this article not helpful? (Check all that apply)
The article is too difficult or too technical to follow.
There is a step or detail missing from the instructions.
The information is incorrect or out-of-date.
It does not resolve the question/problem I have.
How did you find this article?
Please tell us how we can improve this article:
Email Address

new! - Enter your name and email address above and we will post your feedback in the comments on this page!

Support Center Login

Social Media Login

Related Questions

Here are a few questions related to this article that our customers have asked:
Ooops! It looks like there are no questions about this page.
Would you like to ask a question about this page? If so, click the button below!
Ask a Question
n/a Points
2014-08-16 2:25 am

very nice..just copy and paste  and it works :)

n/a Points
2014-09-10 3:31 am

i am using the above code for sending mail but getting error like this:

The following occurred:

    '; // Print each error. echo '

Your mail could not be sent due to input errors.

';} else{echo '

Your mail was sent. Thank you!

Below is the message that you sent.

'; echo "Message from " . $firstname . " " . $lastname . " Phone: ".$phone." "; echo "Red Maple Acer: " . $check3 . ""; echo "Chinese Pistache: " . $check2 . ""; echo "Raywood Ash: " . $check3 . ""; } } //End of errors array ?>


i don't know why this error come when we click on submit button..pls help me soon..

23,312 Points
2014-09-10 7:35 am
Hello Anandita,

Be sure to check your code for syntax errors, particularly the placement of the quotes. Did you cut and paste it as is? It seems to work fine for me when doing that. Did you make any changes?

Kindest Regards,
Scott M
n/a Points
2014-11-11 8:17 pm

I have the same issue as Anandita. I even cut and paste as is yet portions of the php script are getting printed to the page. Any idea what else could be causing this?


11,156 Points
2014-11-11 8:31 pm
It sounds like your code is not being correctly parsed as PHP. Does the file extension a .php file?
n/a Points
2015-01-31 2:44 pm

Hello Anandita,

Probably, you are writing the php code and the html code into the same xyz.html file.

If you are using this instruction with the php script and html code in one file:

<form action="" method="post">

Then it is must that you will get the error which you have reported.

I'll suggest you to make a seperate php file and name it "mail.php". And write the html code in seperate html file and use the following instruction:

<form action="mail.php" method="post">

Once you've done like this, you will not receive any errors. It is a tested method, as I experienced the same but when I added mail.php, everything becomes fine.

I hope this will help you. Though my reply for your comment is too late, but I tried to help you and many others who is facing same error.



n/a Points
2014-09-15 3:24 am

Hi.. Ive problem for make a contact us page. im using such your web for 'post a comment'. its work and nothing error with that. but the comment cannot sent to the email. email cannot received the comment for page contact us. can help me to solve it?



23,312 Points
2014-09-15 8:58 am
Hello Mira,

If you are using just this article, then the email should send through fine. Are you one of our customers? Are you using additional SMTP settings to send your email through the server? If so, they will need to be correct in order to send out.

Kindest Regards,
Scott M
n/a Points
2014-09-16 7:13 am


I am using this entire code but the only problem is that the form is being emailed on refreshing/reloading the page

23,312 Points
2014-09-16 10:16 am
Hello Sak,

Thank you for pointing that out. I found the error and corrected it. It has been tested and will not send an email if it is refreshed before the Submit button is pressed. A more updated version of this article should come out soon with a bit more polish.

Kindest Regards,
Scott M
n/a Points
2014-09-18 4:13 am


i will have to write this whole code in page or two page because it has three partition and php code is starting in partition one and ending in partition 2.

23,312 Points
2014-09-18 9:30 am
Hello Ravi,

You can put all three partitions in the same file. It was only split up on the article to show what purpose each partition serves.

Kindest Regards,
Scott M
n/a Points
2014-09-28 3:37 pm

What if you used radio buttons instead of checkboxes. How would the code look?

I get the html part but the radio validation not sending the value of radio button clicked.


23,312 Points
2014-09-29 9:14 am
Hello Betty,

The checkbox is for when someone may select one or more of the options. Radio buttons force only one selection. Did you have code you wanted us to look at for errors? Replacing the checkboxes with radio buttons needs code modification not only on the form itself, but up where the validation is done.

Kindest Regards,
Scott M
n/a Points
2014-10-17 7:35 am

hello... can i create a home page using php, if yes then can i please get the know how


11,156 Points
2014-10-17 9:02 am
If you are not familiar with PHP, you may want to review some of the PHP articles on W3Schools which will teach you the basics of PHP to get you started.
n/a Points
2014-10-20 4:57 pm

This article is very interesting. Thanks!

I "inherited" the maintenance of some websites that use similar PHP functions for the contact forms, so this helps me understand what is going on. 

BUT, I'm having a big problem with browser compatibility. Any idea what I should check on?  This is driving me nuts!

23,312 Points
2014-10-20 5:04 pm
Hello Lou,

Since the php runs off the server, the functionality should not be affected. The browser incompatibility will likely come in display inconsistencies. These are normally found in the CSS files/statements in the page.

Kindest Regards,
Scott M
n/a Points
2014-10-21 8:32 am

Thanks for the reply Scott.

The websites and forms DISPLAY well in every browser,  But they seem to only actually send the message in Firefox and Chrome. Most messages in IE and some in Safari dont actually go through.  This is driving me nuts.

11,156 Points
2014-10-21 9:35 am
As Scott stated, with it being PHP, the functionality of the form itself should not be affected as all code is executed within the browser. Are you using this same contact form that we have provided within this article?
n/a Points
2014-11-04 9:36 am

 the php runs off the server, the functionality should not be affected. The browser incompatibility will likely come in display inconsistencies. These are normally found in the CSS files/statements. 

n/a Points
2014-12-25 1:09 pm

i want to design an email web page using php, how do i start?

1,293 Points
2014-12-26 10:37 am
Hello Hamman,

Can you provide some more information on what you are wanting to create? Generally a good place to start coding simple websites is W3 Schools.

Kindest Regards,
TJ Edens
n/a Points
2015-01-05 10:09 am

i want to make wesite  using php of my realtives they having a factory so which site i refer to get the knowlegde..i want like this only jst copy and paste so it is easy for me to create website.plz reply me soon plz

20,728 Points
2015-01-05 11:23 am
Hello Ash,

Thanks for the comment. Creating a website using only PHP will
be a copy and paste process no matter what tool you use. There are many applications out there that make it easy to create a website that uses primarily PHP, but I would suggest using WordPress. Our WordPress Education Channel provides a lot of information on how to install and start using the application.

I hope this helps to answer your question, please let us know if you require any further assistance.

Arnel C.
n/a Points
2015-01-30 2:47 pm


I will appreciate the admin on sharing this useful php based code. It really helped me a lot in designing my php contact form. 

I have designed it and tested it successfully. Emails are coming to my email account but unfortunately in the SPAM folder with the tag (Unknown Sender).

I'll be grateful to you for your generous help to me.

Thanks and Sincerely,


20,728 Points
2015-01-30 4:25 pm
Hello Malik,

Sorry for the problem with the form. It looks like the issue is a result of the "FROM" setting for the form. I would recommend that you set it to an email address instead of a website. If you have any further questions or comments, please let us know.

Arnel C.
n/a Points
2015-01-31 2:33 pm

Thank you Arnel C.

I really appreciate your prompt reply. I followed your suggestion and now all the emails are coming to inbox folder instead going to spam. BINGO..!! Thank you.

I'd really like to share the part of php code which I changed.

The original php code has:

$from = "From: Our Site!"; //Site name

Now, just change "From: Our Site!" with a valid email address like below:

$from = ""; //Valid email address

By doing this, email will come to inbox with a valid reference email address and this will prevent email going into spam folder.

Just thought to share, so that some one might get help by this. Any way brilliant work from admins.

Thanks and Sincerely,


n/a Points
2015-02-12 1:26 pm


Advance thanks for your code. every think work fine. but I couldn't receive the information to my email. I used one php file for entire code. If you could help Would be appriciaated.


12,753 Points
2015-02-12 1:58 pm
Hello Kumar,

Thank you for your question. We are happy to help, but will need some additional information. Have you confirmed the email settings you entered are correct?

Have you followed the above guide? Are you having any problems with a step?

Have you reviewed the email logs to confirm if your script is communicating with the email server. (Live support can help you with that if you are on a shared server).

Thank you,
n/a Points
2015-02-13 3:22 pm

I am running this script on a localhost but the email is not being delivered even though the message says mail has been sent. Do I need to make changes to php.ini?

12,753 Points
2015-02-13 7:41 pm
Hello Bob,

Thank you for your comment. PHP errors can be enabled to display and log errors using your local php.ini file.

This can provide more details into what is happening.

Also, be sure to check your spam box/email filter for the test emails.

If you have any further questions, feel free to post them below.

Thank you,
n/a Points
2015-02-24 3:28 pm

Hello all,

I really need help. I don't know where to put my email, so when someone fills in the contact form, they click on the send button and it appears in my mailbox. So my question is; where in this script do I have to add something to receive messages in my mailbox? This script I use is also linked on a jquery. So I have a php form and a jquery. Please help me intelligent people! :D         

In my html I have add this:

<form id="form" action="#">

            <div class="success_wrapper">

              <div class="success">Contact form submitted!<br>

                <strong>We will be in touch soon.</strong> </div>



              <label class="name">

                <input type="text" value="Name:">

                <br class="clear">

                <span class="error error-empty">*This is not a valid name.</span><span class="empty error-empty">*This field is required.</span> </label>

              <label class="phone">

                <input type="tel" value="Telephone:">

                <br class="clear">

                <span class="error error-empty">*This is not a valid phone number.</span><span class="empty error-empty">*This field is required.</span> </label>

              <label class="email">

                <input type="text" value="E-mail:">

                <br class="clear">

                <span class="error error-empty">*This is not a valid email address.</span><span class="empty error-empty">*This field is required.</span> </label>

              <label class="message">


                <br class="clear">

                <span class="error">*The message is too short.</span> <span class="empty">*This field is required.</span> </label>

              <div class="clear"></div>

              <div class="btns"> <a data-type="reset" class="btn">clear</a><a data-type="submit" class="btn">send</a>

                <div class="clear"></div>





The linked Jquery code is this:




return this.each(function(){

var th=$(this)
















".name":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'},

".state":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'},


".phone":{rx:/^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,target:'input'},

".fax":{rx:/^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,target:'input'},





var label=$(this),





return defVal==''?defVal:tmp
























return !el.hasClass(_.notRequiredCl)



var ret=true





return ret



var tmp

return (tmp=el.find(_.targets).val())==''||'defVal')




var th=$(this)


















var val=$('input,textarea',label).val()


return label.length?val==defVal?'nope':val:'nope'






type: "POST",












success: function(){















var th=$(this)




return false






























return false





var th=$(this)








typeof o=='object'










1,293 Points
2015-02-24 11:16 pm

From skimming the code, ownerEmail:'#', is what you would change to be your email but I would suggest contacting the developers of the script just to be sure.

Best Regards,
TJ Edens

Post a Comment

Email Address:
Phone Number:

Please note: Your name and comment will be displayed, but we will not show your email address.

35 Questions & Comments

Post a comment

Back to first comment | top

Need more Help?


Ask the Community!

Get help with your questions from our community of like-minded hosting users and InMotion Hosting Staff.

Current Customers

Chat: Click to Chat Now E-mail:
Call: 888-321-HOST (4678) Ticket: Submit a Support Ticket

Not a Customer?

Get web hosting from a company that is here to help. Sign up today!