Basic Form Submission

In this article we’re going to take a look at basic form submission of a HTML form using PHP. This will allow us to insert data into a database table using a dynamic form.

Prerequisites

Before we get started you will need the following in place

  1. A working web server

  2. Access to a MySQL database

  3. The ability to create tables using an IDE such as MySQL Workbench

Starting point

In order to get started with this task we need a form to work from. This is something we have worked on previously however we’re now going to take a look at developing an online store - albeit a basic online store.

We will start by creating products in the database and displaying products from the database. This forms the Create & Read parts of CRUD functionality.

To get started you can copy and paste this code and save it as a PHP file called create.php. You can create this in the public_html directory of your website for now.

The public_html directory will be based in your website root folder

Read the Creating a new PHP File guide if you’re unsure about how to do this.

<form action="" method="POST">
    <label for="product">Product Name</label>
    <input type="text" name="product" value="">
    
    <label for="price">Product Price</label>
    <input type="text" name="price" value="">
    
    <label for="description">Product Name</label>
    <textarea name="description"></textarea>
    
    <button>Save Product</button>
</form>

Once you have this code copied and your file saved we can move onto the database and PHP elements.

Database Setup

One of the prerequisites or something you should have in place before this article is access to a MySQL database. Now if we look back at the code for the HTML Form (above) you can see we have at least one key piece of information here that will help us create our database table.

This is the name element of each of the input fields. In this example we have input coming from a field with the following names:

  • product (the product name)
  • price (the product price)
  • description (the product description)

As we have these identified we can now go ahead and create our table in MySQL - you can run the following MySQL code in your IDE to create the table or you can use the visual editor to manually create each field.

CREATE TABLE `onlineshop`.`product` (
  `product_id` INT NOT NULL AUTO_INCREMENT,
  `product` VARCHAR(150) NULL,
  `price` DECIMAL(10,2) NULL,
  `description` TEXT NULL,
  PRIMARY KEY (`product_id`));

That’s all we need at this stage. We’re not going to delve too much further into the database setup at this stage but you can see that we have a column for each piece of information from the form, along with a product_id which will form our Primary Key for the table.

Processing the form

We’ve already seen this in a sense by developing our HTML & PHP based contact form. The contact form we said should also be logging the submissions into the database for the time being in case the email doesn’t get sent or gets filtered out by an email blacklist. However let’s now take a look at what the PHP code would look like for this form.

You should add this directly below your form created in the create.php file earlier in this guide. I will break this into smaller chunks to give some background and understanding behind the things we’re putting in place. Later you will see all of this code combined.

  1. The first thing we need to do is tell the PHP server to only act upon any PHP code for the form when it has been submitted. Otherwise there will be nothing to process.

    To do that we create an if statement which checks to see if we’ve been sent a POST request by the server.

<?php
    if($_SERVER['REQUEST_METHOD'] === "POST") {
        // code will only be processed here if we click submit in the form.
    }
?>
  1. The next thing we need to do is gather our information that was sent to us by the product form, however we can only do this **if ** the information has been sent to us.

    We can once again use an if statement to check that we receive the information we expect.

if(isset($_POST['product']) && isset($_POST['price']) && isset($_POST['description'])) {
        // code entered here will only be processed if we have a product, price and description entered
}

In this small snippet of code we’re checking that we have been given the information from the form when the submit button is clicked. We do this by checking if the item is being sent using the isset keyword.

In this case we check for a product, price and a description. Essentially what we’re saying here is that we MUST enter a product name, a product price and a product description. We’re making these fields mandatory.

  1. The next thing we’re going to add is the connection to the database itself. To do this we need to create what’s called a PDO Connection with the MySQL database.

    To do this we will create a try, catch statement which will attempt to connect to the database and log the details we’ve entered.

$servername = "databaseserver.co.uk";
$username = "yourusername";
$password = "yourpassword";
$database = "yourdatabasename";
 
 try {
	
	// attempt to connect to the server
	$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
	
	// set the PDO error mode to exception
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	
	// build the MySQL statement
	$mysql = "INSERT INTO product (product, price, description)
	VALUES ( '$product', '$price', '$description' )";
	
	// pass the query back to PDO
	$newproduct = $conn->prepare($mysql);
	
	// run the query
	$newproduct->execute();
	
	
}
catch(PDOException $e) {
	echo "Connection failed: " . $e->getMessage();
}

In this code we build the MySQL statement, which is just what you would write if querying directly using MySQL Workbench or the likes. We then pass that query to PDO to run it. It’s at this stage that the data gets added to the database.

Full code snippet

Let’s have a look at how this code should look all together.

create.php

<form action="" method="POST">
    <label for="product">Product Name</label>
    <input type="text" name="product" value="">
    
    <label for="price">Product Price</label>
    <input type="text" name="price" value="">
    
    <label for="description">Product Name</label>
    <textarea name="description"></textarea>
    
    <button>Save Product</button>
</form>
        
<?php
    if($_SERVER['REQUEST_METHOD'] === "POST") {
    
        // check that we have data sent to us
		if(isset($_POST['product']) && isset($_POST['price']) && isset($_POST['description'])) {
			$servername = "databaseserver.co.uk";
			$username = "yourusername";
			$password = "yourpassword";
			$database = "yourdatabasename";
 
		try {
	
			// attempt to connect to the server
			$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
	
			// set the PDO error mode to exception
			$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	
			// collect the data into variables for easier access later
			$product = $_POST['product'];
			$price = $_POST['price'];
			$description = $_POST['description'];

			// build the MySQL statement
			$mysql = "INSERT INTO product (product, price, description) VALUES ( '$product', '$price', '$description' )";
	
			// pass the query back to PDO
			$newproduct = $conn->prepare($mysql);
	
			// run the query
			$newproduct->execute();	
		}
		catch(PDOException $e) {
			echo "Connection failed: " . $e->getMessage();
		} 
	}
}      
?>