How to Insert Data Into a Table of a MySQL Database From an HTML Form



PHP


In this tutorial, we will show how to insert data into a MySQL table of a database from an HTML form.

The data which a user enters into a form, such as in the one below, will go straight into a MySQL database, so that we store a the user-entered information directly to a database.

This could be useful whenever you want to store information directly to a database.

Below is a form which asks a user for his first name, city, and country.













How do we put this data into a MySQL Database so that we can have a table containing everyone who enters to join this email list?

MySQL

The first thing you must do is create the MySQL table in which you are going to transfer the data to. Choose or create the database which is going to contain the table and then create the table. In this example, the table will be called email_list.

The MySQL code to create the table is:

CREATE TABLE (first_name VARCHAR(50), last_name VARCHAR(50), email VARCHAR (50));

Once this table is created, we now create the PHP code. To create the PHP code, we must first examine the HTML code of the form.

HTML Code



The HTML code creates the HTML form. This form has 3 fields: first name, city, and country. It also has a submit button.

PHP code is added to this HTML form, so that if any of the fields are left empty after the submit button is clicked, the statement is output, "This field cannot be left empty".

So the next thing we do is create the PHP code that adds functionality to this HTML form.

PHP Code



This PHP Code is separated into 7 blocks in order for us to review each part of the code and know what each part is doing.

Block 1 is where you enter all of the information to your MySQL server. This is so that you can later make a connection to your server to connect to the table of your database to insert the user's info into.

Block 2 is the code used to retrieve the information that the user entered into the HTML form field. All of the user's information is saved within the PHP variables.

Block 3 is the code used to make a connection to the MySQL server and the desired database you would like to connect to.

Block 4 is the code that actually executes the insertion of the data into the database.

Block 5 closes the database connection.


HTML Comment Box is loading comments...