Home » Learn Code » PHP » How to Connect HTML Form to MySQL Database using PHP

How to Connect HTML Form to MySQL Database using PHP

how to connect html form to mysql database using php

Creating the HTML form is very easy. But connecting that HTML form to the MySQL database using PHP can be a little bit complicated for beginners. But this is not rocket science, trust me you can do it very easily. This tutorial will teach you, how to connect HTML Form to MySQL database with the help of PHP.

After reading this guide, you will be able to:

  • Save HTML form entries in database.
  • Create MySQL database
  • Create tables in MySQL Database
  • Connect HTML to MySQL database using PHP
  • Create PHP file to get entries

So, let’s get started.

First and foremost, the most important question that arises here is. What do we need? We need just two things a text editor and a XAMPP server software.

So what are we going to do? Let’s see the steps that we are going to perform in this article. You can jump to any of these below steps by clicking:

  1. Firstly, we’ll install and run XAMPP on your PC or laptop.
  2. Then next, create MySQL database to Connect to HTML Form.
  3. Create a table in MySQL database to Save HTML Form Entries.
  4. Create HTML Form.
  5. After that we’ll Create a PHP file to get HTML form entries.
  6. Lastly, we will create a Connection to Save HTML Form Data in MySQL Database.

How to Connect HTML Form to MySQL Database using PHP

Let’s begin with our first step.

1. Install and Run XAMPP on Your PC to Create MySQL Database for HTML Form

You can download XAMPP from the apachefriends.org website. It is open-source webserver software and freely available. XAMPP allows us to create a server environment on our local computer.

We need XAMPP because PHP and SQL are server-side languages, so we need a server. Also, to save HTML form entries in the database we need a MySQL database. XAMPP allows us to create a MySQL database and run PHP.

Download and Install XAMPP for Windows

There are other software’s like WAMP and MAMP etc available to create a web server. But I selected XAMPP because it is available in multiple operating systems like Windows, Mac OS, and Linux.

Tip: If you want to know more about XAMPP then check this guide on WordPress installation on localhost using XAMPP. In this guide, you will also learn more about what is XAMPP? And how to download and install XAMPP? And if you are a WordPress user then this guide will really help you.

Now let’s go to the main topic.

After downloading XAMPP, go ahead install and run XAMPP on your PC or laptop. When you will open XAMPP, just run Apache and MySQL server as shown in the image below.

Run Apache and MySQL on XAMPP

Now you have been created a local web server on your computer. It will allow you to run and execute PHP and SQL code. Now we can create a MySQL database. To connect HTML form to MySQL database using PHP, we need a database.

Minimize XAMPP. Don’t close it.

Let’s see the second step.

2. Create MySQL Database to Connect to HTML Form

To do this, open your browser. And type localhost/PHPMyAdmin in your browser’s search bar and press enter. As shown in the image below.

open phpmyadmin page

This will take you to the PHPMyAdmin page. Where we will create a MySQL database to save HTML form entries.

A quick introduction to PHPMyAdmin: It is a free and most popular administration tool for MySQL databases. The benefit of using PHPMyAdmin is that we can create and manage databases without having any knowledge of SQL language.

Now see the next image below. In this image, on the left side, all databases are listed. Just click on the New button to add a new database.

Create Database

On the next page, you will choose the name of your database. After that click on Create button. You can give any name to your database. I will give it a form_entriesdb name. You can use the ‘_’ underscore sign in your name. As shown in the image below.

Create New MySQL Database for HTML form

Now the database has been created successfully. On the next page, you will create a table in your database. Don’t close the page. Let’s see the third step of this lesson.

3. Create a Table in MySQL Database to Save HTML Form Entries

After creating a MySQL database for the HTML form, you will be redirected to the tables page. Just see the image below.

Give a table name. In my case, I give a name to my table (contactform_entries). Then, enter how many columns should be in the table.

Create a Table in MySQL database

Here remember these columns are every HTML form input that the user will enter.

In case if you have three input fields like Name, Email, and Message. Then there will be four columns in the database table like Id, Name, Email, and Message.

So, we will have three input fields in our HTML form. I will enter 4 here. Because id will auto-increment and tell us how many entries have been saved. It is for our convenience only.

When we export a database table in an excel file. The id does not show by default if we do not create a column with the name id.

After entering the table name and number of columns, click the Go button to create a table.

Now see the next image below. Here we will enter our column details.

Enter name of columns

Every column should have a name, data type, length of characters, and so on. So we can store the data according to our column in the database.

Fill in all the details as I have given below.

NameTypeLength/ValuesDefaultNull Index
idINT20NonePrimary
name_fldVARCHAR20None
email_fldVARCHAR20None
msg_fldTEXT1000None

See it will look like this in the image below. Remain the other fields as it is. Only fill in the details for Name, Type, Length, and Null Index for only id.

Column details in MySQL Database

Then click the Save button located at the bottom to save.

Only one thing remaining then we will go to our HTML form.

Create a User of this MySQL Database and Assign Priviliages

As you can see in the below image, go to the Privileges tab.

Privilege's Tab in Database

In the Privileges tab, we will create a user for this database. And these details will be needed during the connection of the database using PHP.

Add New User for MySQL Database

After clicking on Add user account, provide these details.

Remember these details: I created a user name with the name formdb_user, then in the dropdown, I selected localhost, and then the password abc123.

Now, click the check to assign all privileges to this user. And then scroll down to the end of the page. And click the Go button to save.

create a user and assign all privileges

Now the database part is done.

Before going to the fourth step. We have to create a folder with the name testsite in htdocs folder located in XAMPP. In that folder, we will place our code files.

Create a Folder in htdocs and Name it ‘testsite’

To do this, open the XAMPP folder where you installed it. In the XAMPP folder, find a folder named docs. This is the folder where we place our website files on the local server.

Open it and create a folder and name it testsite. In this folder, we’ll place our HTML form, CSS stylesheet, and a PHP file. So that we can access them on our PC.

Let’s see the fourth step. I will not create the whole HTML form, just will give you some code to copy-paste and information. So, don’t be a bore.

4. Create HTML Form

Open your text editor. I have a visual studio editor. Which one do you have? Just open that text editor and paste this HTML form code given below.

The HTML form will look like this on your PC.

HTML form to connect to mysql database

We’re going to connect this HTML form with the MySQL database. So we can receive the contact form entries and save them to our database.

Now copy the HTML form code given below.

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Contact Form</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div class="form">
    <form method="POST" action="form.php">
        <h1>Contact Form</h1>
        <table>
            <tr>
                <td>
                    <label for="fname">Full Name:</label><br>
                    <input type="text" name="fname" placeholder="John Doe" id="">
                </td>
            </tr>
            <tr>
                <td>
                    <label for="email">Your Email:</label><br>
                    <input type="email" name="email" placeholder="[email protected]" id="">
                </td>
            </tr>
            <tr>
                <td>
                    <label for="msg">Your Message:</label><br>
                    <textarea name="msg" placeholder="Type your message..." id="" cols="30" rows="10"></textarea>
                </td>
            </tr>
            <tr>
                <td>
                    <input type="submit" name="submit" value="Send Message">
                </td>
            </tr>
        </table>
    </form>
</div>
</body>
</html>

Copy CSS Code and paste it in your text editor with a .css extension file.

*{
    box-sizing: border-box;
    margin: 0;
}
div.form{
    height: 100vh;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    font-family: Arial, Helvetica, sans-serif;
}
form input[type=text], input[type=email], textarea{
    width: 600px;
    font-size: 20px;
    padding: 8px 6px;
    border: none;
    border-bottom: 3px solid #5f5f5f;
    background-color: #f1f1f1;
}
form input[type=text]:focus, input[type=email]:focus, textarea:focus{
    outline: 1px solid #5f5f5f;
}

form input[type=submit]{
    font-size: 20px;
    padding: 8px 26px;
    border: none;
    background-color: black;
    color: white;
    border-radius: 4px;
}
form input[type=submit]:hover{
    background-color: #0e42de;
}
textarea{
    resize: none;
}

After copying and pasting these codes, just save them. And the code files should be in our testsite folder.

Now, we have a beautiful HTML form. It’s time to write some PHP code to get form entries and send them to the database.

One thing to know, you can access this form in your browser by typing localhost/testsite. Just make sure XAMPP is running. And Apache and MySQL are running. Otherwise, this may show an error.

HTML Form

You can see this by clicking on send message button. Nothing happens! When we will connect this form to the MySQL database, it will work.

Let’s see the fifth step. Only two steps remain.

5. Create a PHP file to Get HTML Form Entries

Here you should look at the code very carefully. It’s an important part to learn. First of all, create a PHP file in your text editor with name form.php.

After creating form.php in your text editor, just copy-paste the PHP code given below. Then, see code explanation.

<?php
    if(isset($_POST['submit']))
    {
        $name = $_POST['fname'];
        $email = $_POST['email'];
        $message = $_POST['msg'];
    }
?>

Code Explanation: We can get HTML form entries through $_GET and $_POST methods. I used $_POST because it is more secure.

I get all the HTML form inputs through $_POST[‘name_attribute_value’] and store them in 3 different variables.

Let me tell you one thing if you don’t know. In square brackets of $_POST, we use the value of the name attribute of HTML. Like in the image below.

name attribute in html form input

Just make sure that the action=”form.php” attribute is specified. So that the form entries can go to the form.php file after a click on send message button. Otherwise, it will show an error.

Now we have got entries through PHP. It is time to make a connection to the MySQL database. Then, we’ll send these entries to the MySQL database.

Let’s go to the last step of this guide.

6. Create a Connection to Save HTML Form Entries in MySQL Database

To do this paste the below code in your PHP file.

<?php
    if(isset($_POST['submit']))
    {
        $name = $_POST['fname'];
        $email = $_POST['email'];
        $message = $_POST['msg'];
        
        //database details. You have created these details in the third step. Use your own.
        $host = "localhost";
        $username = "formdb_user";
        $password = "abc123";
        $dbname = "form_entriesdb";

        //create connection
        $con = mysqli_connect($host, $username, $password, $dbname);
        //check connection if it is working or not
        if (!$con)
        {
            die("Connection failed!" . mysqli_connect_error());
        }
        //This below line is a code to Send form entries to database
        $sql = "INSERT INTO contactform_entries (id, name_fld, email_fld, msg_fld) VALUES ('0', '$name', '$email', '$message')";
      //fire query to save entries and check it with if statement
        $rs = mysqli_query($con, $sql);
        if($rs)
        {
            echo "Successfully saved";
        }
      //connection closed.
        mysqli_close($con);
    }
?>

Note: To prevent your database from SQL injection attacks. Kindly create and use your own unique database name, username, password, and table field names. Don’t copy everything the same.

Code Explanation:

  1. On line number 8 of code given above, I stored the hostname, username, password, and database name in variables. We have created these details in the third step of this guide. You can scroll up and check this.
  2. After that, I created a connection to the database with the mysqli_connect() function. In this function, I specify the MySQL database details stored in variables.
  3. Then, I check the connection through if statement.
  4. After that I create SQL query that is located on line 22 of above given code. In that SQL query, I specify table name, column details and their values that we got from HTML form.
  5. Then, I fired a query to store mysqli_query() function to store the data in database. Then, I checked it with if statement. Mean it has been stored in database or not.
  6. Lastly, I closed the connection with mysqli_close() function. In this function, I specify the variable $con where our database details are stored.

All Done! Thank God! This was an in-depth guide.

I tried hard to teach you. If I missed something then please tell me in the comment section below.

Conclusion:

To save HTML form entries in the MySQL database using PHP, you will do just 6 simple steps.

#1: Install XAMPP on your system. Then, run Apache and MySQL in XAMPP. (Keep it running during the whole process otherwise, the code will not work in your browser).

#2: Create a MySQL database.

#3: Create a Table in the MySQL database where your HTML form entries will save.

#4: Create HTML form. (The HTML form code is given above with an explanation.)

#5: Create a PHP file in your text editor.

#6: Lastly, create a Connection to save HTML form entries in the MySQL database.

Also, read CSS flexible box complete with examples. I used CSS flexbox property in HTML form. This will be a helpful guide for you. And I used table tags in this guide to set HTML form fields. For this, read how to create tables in HTML.

Hope you will like it. Tell me in the comment section below.

2 thoughts on “How to Connect HTML Form to MySQL Database using PHP”

    1. Hi Damon,
      Check your steps and code again for any mistakes.
      Make sure
      1. XAMPP is ON and Apache + MySQL running during the whole process.
      2. You need just 3 files index.html, styles.css & form.php.

Leave a Reply

Your email address will not be published. Required fields are marked *