MySQL
Php

How to insert data into mysql database using PHP form and then send mail – Part 1

Beginner 1 hr
view more posts

This is a beginner’s tutorial on how to use a PHP form with mysql database to save data and send email. Most of the times when we work on basic websites whether it is useful or not the client ask us to add a ‘Enquiry Form’. An enquiry form that sends mail to the client’s mail id. Sometimes when working on a CMS where a mysql database (or any other database) is used the clients require to store the enquiry form data into their database. For freelance beginners this is a huge challenge and this tutorial will make you confident next time you sign a deal.

This is a two part tutorial. In the first part we look at how to process the form and in the SECOND PART we look at how to insert and send mail using PHP. I understand the whole crust is in the second part but if you are a beginner I strongly recommend you finish the first part and then go to the SECOND PART.

In this tutorial we dive in deep to understand the do’s and dont’s while connecting with the MySQL database. We also learn about the naming conventions and how to increase the security of your code. Feel free to ask any questions in the comments section and we assure you that it will be cleared.

Creating a PHP Form

Take a look the code below. I will explain it one line at a time.

<form class="form" method="post" action="process.php">
    <p>
        <label>Name *</label>
        <input type="text" name="enq_name" placeholder="Full Name" required />
    </p>
    <p>
        <label>Mobile *</label>
        <input type="number" name="enq_mobile" required />
    </p>
    <p>
        <label>Email *</label>
        <input type="email" name="enq_email" required />
    </p>
    <p>
        <label>Message</label>
        <textarea rows="5" name="enq_message" cols="15"></textarea>
    </p>
    <input type="submit" name="enq_submit" value="Apply Online" />
</form>

There is nothing PHP about this form. It’s a simple straight forward HTML code. The PHP comes in later when we need to capture the data that is sent from the form.

Let’s take a look at the line one.

<form class="form" method="post" action="process.php">

We declare the ‘form’ tag to let the browser know that we are working with a form now. Then comes the ‘form’ class for CSS purpose. The ‘method’ attribute is the way in which the ‘form’ tag sends the information. There are two types of ‘method’, one is ‘GET’ and second is ‘POST’. The ‘action’ attribute tell the form tag where to POST the information. In our case we will be posting it to ‘process.php’.

From the second line on you do not require explanation if you are familiar with HTML. However there is one thing that you have to look at. Lets take a look at the line below.

<input type="text" name="enq_name" placeholder="Full Name" required />

We create an input tag with its many attributes. The attribute to be noted here is ‘name’. This is very important as it acts as the key to the value entered by the user in the input tag. In simple words – consider ‘key’ to be a container which is unique, hence you cannot have two similar values for the ‘name’ attribute. A key can carry values assigned to it and this happens when the user clicks on the submit button. It is advisable to prefix the value of ‘name’ attribute so that it does not clash with any other plugins or codes when you are working on a large project.

Now for the submit button.

<input type="submit" name="enq_submit" value="Apply Online" />

Here even the submit button has a ‘name’ attribute and a key given to it so that we can use it later.

Processing a PHP form.

Usually this means validating a form and then checking if the values entered have any malicious codes that will affect our database. Once we have done this we see what to do with the data that was sent via POST method.

This has many small steps involved. Don’t be scared its fairly simple. Let’s go one at a time. (We will talk about validating the form a little later as it in itself is a huge topic and we have different ways to do that.)

Creating the database

If you do not know how to create a database kindly watch this video.

Once the database is ready it is time for us to create the tables. Check out the following video to see how a table is created in MySQL using phpMyAdmin.

This is our resultant table.

(Remember to prefix your column names so that they are unique and do not clash with any other columns. In this case its ‘nfrm’ short hand for ‘new for’).

Connecting to the database.

As much as it sounds complicated it is fairly simple. It’s just three lines of code actually and you will be using this a lot if you are a PHP developer. So try to memorize this as it will be handy.

<?php
    $connection = mysql_connect('server', 'mysql_user', 'mysql_password');
    if (!$connection){
        die('Could not connect: ' . mysql_error());
    }
?>

We use the function mysql_connect which opens a connection to the MySQL server. This function has three attributes server, mysql_user, mysql_password. Server is the location of the MySql database. Usually its ‘localhost’, so replace ‘server’ with ‘localhost’. Then while creating the MySql database you would have created a username and password for it. Replace them in their appropriate places. (If you don’t know what they are kindly contact your hosting service provider or take a look at this video).

Once the MySQL connection is made we need to be able to access it. So we assign the result of mysql_connect function to a variable called $connection.

If all goes well then the connections is made. But if something goes wrong how do you find it out? We need a way to know what went wrong. Hence we do an if statement to find what went wrong. If the variable $connection is not set then die and print the mysql_error(). Hence the following two lines.

if (!$connection){
        die('Could not connect: ' . mysql_error());
}

Thus you make a proper database connection.

Fetching the POST data.

Once the user clicks on submit button the HTML form sends data via the POST method using the $_POST global variable, in an array. Just like accessing any Array variable you access the $_POST variable too using PHP.

Remember the key values we set to the name attributes in the HTML form? Because we set it, its easy for us now to know the key values inside the $_POST array. So let start fetching the data now and assign it to different variables.

Earlier when we were creating the form we had assigned name attribute to the submit button too. Well here is the reason. All HTML content are visible when we view the source of a page. So for the hackers it is easy to see where we are processing the page (in our case is process.php). It is in this page that we have the username and password to out MySQL database. So it becomes a very easy target and hence the hackers usual try and manipulate the page. So as a part of security it is best practice to check where the variable has come from and then start processing the page. Another method is to store the connect details in a different PHP page and reference it in our processing page.

So we first check if the variable $_POST(enq_submit) has been set. If yes then we process the rest, else we just display a message asking them to use the form.

<?php
    if (isset($_POST['enq_submit'])){
        //Process the rest
    } else {
        echo("Kindly use the form to submit the data!");
    };
?>

Now to the processing of the $_POST global variable. Here we fetch each key value and assign it to a different variable, usually with a different prefix. We can assign to the same variable like this:

$enq_name = $_POST['enq_name'];

But again the hackers are aware of the key value and there are chances they manipulate it. So we change the prefix and assign them. At every point we need to be careful not to reveal any information. Hence the following code.

<?php
    if (isset($_POST['enq_submit'])){
        $nfrm_name = $_POST['enq_name'];
        $nfrm_mobile = $_POST['enq_mobile'];
        $nfrm_email = $_POST['enq_email'];
        $nfrm_message = $_POST['enq_message'];
    } else {
        echo("Kindly use the form to submit the data!");
    };
?>

Thank you for keeping up till now. In the SECOND PART we look at how to insert and send mail using PHP. The complete crest of this tutorial is in the second part. So keep reading.

See you in the SECOND PART. And if you have doubts kindly ping me in the comments. Thanks again for reading.

Latest Comments

3 responses to “How to insert data into mysql database using PHP form and then send mail – Part 1”

  1. mkkhan says:

    Hi sir, can you provide me zip package of this code ready to use
    i am new in php
    thanks in advance

  2. Koks says:

    Hi,

    It would be great if you provide your full code in zip

    cheers!

Leave a Reply

comment on this article