Simple PHP Contact Form to Send Email & Storing In MySQL Database

This is simple PHP Contact Form to send E-Mail through your website’s contact page. First, we should have an HTML form to collect data from users. And this data should be sent to PHP for sending email.

This form should contain these elements, you can add more input fields also based on your requirement. I’m using these fields Name input, email, subject, message.

First I’ll send email, then I’ll extend the features of this contact form to save the submitted queries in database. If you want you can include captcha also for security purposes.

1. Send Email after submitting contact form through PHP

Add HTML Form Code with styles.

Next add the styles, I’m using bootstrap styles and some custom styles. Add this code inside your head section

Adding styles to form

Add this custom styles sytels.css file

Then add this HTML in body section of your document.

Adding Form HTML

This below code contains name field, email field, and subject line and message text area. And here we are using HTML5 form validations for email and required fields.

PHP Code to Send Email

First checking the input fields contain data. If they have data, setting the variables and sending email with PHP mail function.

If the mail sent successfully, displaying successful message in browser.

2. Insert Submitted Contact Form queries in MySQL Database Using PHP

Create MySQL Database table

Connect to Database in PHP

Create connect.php file to connecting to MySql database in PHP.

Insert submitted queries in MySQL Database

We will insert into database upon sending email on true condition we will execute these statements in php.

Complete code of Simple PHP Contact Form to Send Email

I hope this code helped you to create simple contact form in PHP to send emails and to store submitted queries in database. If yo have any issues, let me know through the comment form below.

Incoming search terms:

  • login and registration form in php source code

Check Your Website Rankings

Vivek Vengala

Vivek Vengala is a Online Entrepreneur, Web Developer from Hyderabad India.

Click Here to Leave a Comment Below 2 comments


thank you very much for this very helpfull article
but the input is not sanitized,
so if i put special characters in it it breaks the code.

I’m sure you heard of SQL Injection, so how can i fix this example to be more robust?


    Vivek Vengala

    Hi Marcel,

    Thanks for letting me know, I’ll make the necessary changes to code.

    You can use mysql_real_escape_string PHP function to stop SQL Injection.


Leave a Reply: