How to Insert Data Into 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, last name, and email address.









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 shows that once the submit button of the form is pressed, we are going to be taken to the addcontact.php page and this file will be executed.

So the next thing we must do is create the addcontact.php page.

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 to insert the user's information into the table specified in the $table variable. This is the table that will hold all information that users enter to join this email list.

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

Block 6 is the code, if all goes right and there are no errors, that prints the statement that the user has been added to the email list. So their data is now saved in the database.

Block 7 closes the database connection.


HTML Comment Box is loading comments...