How to Insert Form Data into a Database Using HTML & PHP
Tags: html, php, mysql, database
Published: 2022-08-21 05:12:00

Collecting customer form data is a common task in web development. Contact forms make your site more professional and send a clear signal that you're interested in doing business with your potential clients. The lack of one could make your business seem outdated or unprofessional. People are more likely to patronize your products if you're highly accessible. This is a great way to increase your business's visibility.

<strong>Other reasons to implement a contact form:</strong>

1. It makes your site more professional
2. Security
3. Makes yourself more reachable
4. Automate email responses

Today, we will be learning how to insert customer form data into a MySQL database using HTML and PHP. We will be creating an HTML form and a PHP script to insert the data into the database using `phpMyAdmin`.

## Prerequisites:
- [XAMPP Server](https://www.apachefriends.org/download.html)
- [PHP](https://www.php.net/downloads.php)
- [HTML](https://www.w3schools.com/html/default.asp)
- [MySQL](https://www.mysql.com/downloads/)

## Instructions:
As an example, the first thing we will need to do is create our `HTML` form. An HTML Form is a document that stores information about the user's interaction with a website. The form is a way for the user to send information to the database.

```html
<form action="/action_page.php" method="POST">
  Form Elements...
</form> 
```
The `action` attribute tells the form where to send the data. The `method` attribute tells the form how to send the data.

## Connecting to the Database
A database is a collection of data. It is a way to store and retrieve data from a computer or server.

Xampp stands for "Extended Apache MySQL Platform". It is a free and open-source software that allows you to run a database server on your computer. It utilizes MySQL, Apache, PHP and Perl as its database engine, and it is free to use.

## Example PHP Code:
```php
<?php

// Set your connection variables
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

// Create connection
$conn = new mysqli($servername,
	$username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
	die("Connection failed: "
		. $conn->connect_error);
}
// Insert into appropriate table
$sqlquery = "INSERT INTO table VALUES
	('John', 'Doe', 'john@example.com')"

// If the connection is successful, run the query
if ($conn->query($sql) === TRUE) {
	echo "record inserted successfully";

// If the query is not successful, display the error message
} else {
	echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
```

## Processing form data:
We can collect the form data submitted through our HTML form that we're going to create. We can use the `$_REQUEST` variable to collect the data.

```php
<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

	// collect value of input field
	$data = $_REQUEST['val1'];

	if (empty($data)) {
		echo "data is empty";
	} else {
		echo $data;
	}
}

// Closing the connection.
$conn->close();

?>
```

## Setting up your Xampp Server
In order to successfully connect to the database and send over our form data, we need to set up our Xampp server to accept the incoming data:

- First we need to start our Xampp server.
- Navigate to `localhost/phpmyadmin`.
- Create a database name of `SampleDB` and a table name of `SampleTable`.
- Create our HTML and PHP files in our Code Editor. I am using [Visual Studio Code](https://code.visualstudio.com/).
- Submit our data through the form we created. 
- Check the results and verify that all data was successfully inserted.

## Process:

First, you'll want to make sure that you already have [XAMPP Server](https://www.apachefriends.org/download.html) installed on your local machine. Once it's installed, let's begin by first opening up our Xampp application. In my case, I am using a Macbook Pro so things may look a little different if you're using Windows or another operating system. You'll want to make sure you have the following services running when you open up your Xampp application:
1. <strong>MySQL Database</strong>
2. <strong>Apache Web Server</strong>

<img src="https://i.ibb.co/MVZL4xL/xampp.png" alt="xampp-image">

Now we can navigate over to `localhost/phpmyadmin` and create a database and table.
- Click on `New` and then type in the name of your Database. We are going to name our database `SampleDB`. Once complete, go ahead and click the `Create` button.

<img src="https://i.ibb.co/PhMmtnt/Screen-Shot-2022-08-22-at-12-24-24-PM.png" alt="create-Sample-DB" border="0" />

Next we can create the table we want to use named `SampleTable`. Make sure to set the number of columns to 5. Once complete, click the `Create` button.

<img src="https://i.ibb.co/QnLC07c/Screen-Shot-2022-08-22-at-12-29-01-PM.png" alt="sample-Table" border="0">

Now that our Database and Sample table is created, we can enter our columns and click on save.

Make sure you enter the correct data type for each column.
- `first_name`
- `last_name`
- `gender`
- `address`
- `email`

Also, make sure to add the appropriate type of `VARCHAR` to each item as well.

<img src="https://i.ibb.co/Y0X9DjS/Screen-Shot-2022-08-22-at-12-20-53-PM.png" alt="table-Valuespng" border="0">

## Create the html form
Now it's time to create our HTML form. We will be using this form to send the data to our database. 

Filename: `index.php`
```html
<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Sample Form</title>
   </head>
   <body>
      <center>
         <h1>Storing Form data in Database</h1>
         <form action="insert.php" method="post">
            <p>
               <label for="firstName">First Name:</label>
               <input type="text" name="first_name" id="firstName">
            </p>
            <p>
               <label for="lastName">Last Name:</label>
               <input type="text" name="last_name" id="lastName">
            </p>
            <p>
               <label for="Gender">Gender:</label>
               <input type="text" name="gender" id="Gender">
            </p>
            <p>
               <label for="Address">Address:</label>
               <input type="text" name="address" id="Address">
            </p>
            <p>
               <label for="emailAddress">Email Address:</label>
               <input type="text" name="email" id="emailAddress">
            </p>
            <input type="submit" value="Submit">
         </form>
      </center>
   </body>
</html>
```

## Create the php script
Now we need to create our PHP script. This is the script that will process our form data and insert it into our database. 

Filename: `insert.php`
```php
<!DOCTYPE html>
<html>

<head>
	<title>Insert Page page</title>
</head>

<body>
	<center>
		<?php

		// servername => localhost
		// username => root
		// password => empty
		// database name => staff
		$conn = mysqli_connect("localhost", "root", "", "sampleDB");
		
		// Check connection
		if($conn === false){
			die("ERROR: Could not connect. "
				. mysqli_connect_error());
		}
		
		// Taking all 5 values from the form data(input)
		$first_name = $_REQUEST['first_name'];
		$last_name = $_REQUEST['last_name'];
		$gender = $_REQUEST['gender'];
		$address = $_REQUEST['address'];
		$email = $_REQUEST['email'];
		
		// We are going to insert the data into our sampleDB table
		$sql = "INSERT INTO sampleDB VALUES ('$first_name',
			'$last_name','$gender','$address','$email')";

		// Check if the query is successful
		if(mysqli_query($conn, $sql)){
			echo "<h3>data stored in a database successfully."
				. " Please browse your localhost php my admin"
				. " to view the updated data</h3>";

			echo nl2br("\n$first_name\n $last_name\n "
				. "$gender\n $address\n $email");
		} else{
			echo "ERROR: Hush! Sorry $sql. "
				. mysqli_error($conn);
		}
		
		// Close connection
		mysqli_close($conn);
		?>
	</center>
</body>

</html>
```
Great! Now we can submit our form data to our database but first we need to save our `index.php` and `insert.php` files inside of our `htdocs` folder located inside our Xampp directory. 

## HTDOCS Folder

We can access this folder by opening up our Xampp application and then clicking on `Open Application Folder`.

<img src="https://i.ibb.co/1v57qSR/open-folder.png" alt="open-folder" border="0">

This will open up our Xampp files directory. Navigate to the `htdocs` folder and copy your `index.php` and `insert.php` files directly into this directory. This will overwrite the existing file. Now we can head over to `localhost/index.php` to fill out the form submit it to our database.

<img src="https://i.ibb.co/FBQKvmT/Screen-Shot-2022-08-21-at-1-00-31-AM.png" alt="store-Form-In-DB" border="0">

Fill out the form and then click `submit`. Great! it looks like our data has been successfully stored in our DB.

<img src="https://i.ibb.co/6wvYXxX/Screen-Shot-2022-08-22-at-12-34-22-PM.png" alt="form-Submit" border="0">

Head over to `localhost/phpmyadmin` and select your database to ensure that our data was successfully inserted.

<img src="https://i.ibb.co/rFLVTH6/Screen-Shot-2022-08-22-at-12-37-13-PM.png" alt="dashboard" border="0">

## Conclusion

You have just completed the basic steps to store data in a database using HTML and PHP. You can now use this method to create any kind of form you like and attach it to a phpMyAdmin database.

<hr>

🤝 Thank you so much for taking time out of your day to read this Article! I hope it helped you out and you learned something new today! Please leave a comment if you have anything you'd like to add. I'd love to hear from you!