Web Programming TutorialsPHP,MYSQL and HTML Forms

PHP,MYSQL and HTML Forms

In the last tutorials we studied PHP and PHPmyAdmin tool to use MYSQL. We have also learned to insert, select, update, delete, etc into MYSQL database using PHP, but it was just a hard code. So today we will learn to insert data into the database using HTML forms.

So follow the steps given below.

    1. Create a new folder named AddEmloyee into the htdocs folder which is in the xampp folder located in C drive.
    2. Open a new notepad++ document and save it as index.php in the newly created AddEmployee folder in the htdocs folder.
    3. Write the following html code in index.php file:
<!DOCTYPE html>
<html>
<head>
<title>Add Employee</title>
</head>
<body>
</body>
</html>
    1. Open the browser and type localhost/AddEmployee in the address bar. You will see the following output.

 

initial_output
fig 1

    1. Now our next step is to add a HTML form in our index.php page. So write the following code to design a HTML form in the
      <body>---</body>

      tag.

<h1>Add Employee</h1>
<form method="post" action="process.php">
<label>First Name:</label>
<input type="text" name="first_name"/><br/>
<label>Last Name:</label>
<input type="text" name="last_name"/><br/>
<label>Department:</label>
<input type="text" name="department"/><br/>
<label>Email:</label>
<input type="email" name="email"/><br/>
<input type="submit" value="Add Employee"/>
</form>
      • Here we have created an HTML form to accept the first name, last name, department and email id from the user.
      • We want to insert this information in the employees table of company database.
      • This will be done using PHP.
      • We use form tag to create a form in HTML. This tag has attributes method and action.
      • The attribute method has 2 values viz. “get” and “post”. Among this get method shows all the data accepted from the user from the form in the address bar of the browser when clicked on submit button and post method hides all the data while taking it to another page. Thus post method is reliable from security point of view.
      • The action attribute allows the data to be taken to the page specified as its value. In this case the data will be taken to process.php page.
      • The form will look as shown below:

 

form_output
fig 2

    1. The form looks ugly, so let’s apply some styling to it. Write the following code between the
      <head>---</head>

      tags.

<style>
	label
	{
		display:inline-block;
		width:100px;
		margin-bottom:10px;
	}
</style>
      • Here, we have applied a width of 100 pixels and bottom margin of 10 pixels to the labels.
      • The display:inline-bolck; allows the labels and text boxes to be arranged one below the other in a straight line.
      • The output of form after styling is shown below:

 

styled_form_output
fig 3

    1. Now we have process.php as the value given to the action attribute of the form. This process.php file will handle the insertion of the information accepted by the html form into the database.
    2. So open a new notepad++ document and save it as process.php in the AddEmployee folder.
    3. Write the following code in process.php file:
<?php
print_r($_POST);
?>
      • The function print_r() allows the data to be printed in an array format.
      • Now let us see what is $_POST?
      • $_POST is one of the global variables in PHP. It stores all the parameter values accepted from the user in the form and takes it to the processing page.
    1. Let us demonstrate it. Put values in the textboxes as shown below:

 

filled_form
fig 4

      • Now, click on the button Add Employee. It will take you to process.php page as shown below:

 

$_POST_values
fig 5

      • Here we see that process.php page has an array that contains all the values entered by the user in the Add Employee form.
      • How did these values come on this page?
      • We have discussed earlier that all the values entered by the used are stored in the global $_POST. It depends, if you would have used method get for the form, all these values would have been stored in the global variable $_GET. And since it is global, it can be accessed anywhere in session.
      • These values are displayed using print_r() fuction which is used to display arrays in its name-value format.
    1. If we try to print simply the first name Dave on process.php, we can do it by writing the following code:
<?php
echo $_POST['first_name'];
?>
      • The name of the input field first_name is used to fetch the value from the variable $_POST.
      • The output is shown below:

 

first_name_displayed
fig 6

    1. As we can display the values on the page by fetching it from the variable $_POST, we can also store them in different variables to insert into the database.
      • So write the following code in process.php page to store values in $_POST variable into five different variables:
<?php
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$department=$_POST['department'];
$email=$_POST['email'];
?>
    1. This will store all the values in different respective variables.
    2. We have all the values that are to be inserted. So now we need to connect to the database.
      • To connect to the database we need to write the connection code as follows:
<?php
//create connection
$connect=mysqli_connect('localhost','root','12345','company');

//check connection
if(mysqli_connect_errno($connect))
{
	echo 'failed to connect!';
}
?>
      • We can write this code in the process.php file itself. But if we have one more html form say Add Product and we want to insert the information accepted through it in the products table of the same database, we again have to write the same connection code in the page processing that form also.
      • So to avoid writing the same connection code every time it is a good practice to write the code once in a separate file and then include that file wherever you need it.
      • So open a new notepad++ document and save it as database.php in the AddEmployee folder.
      • Now write the above given database connection code in the database.php file and save it.
    1. Now to include the file database.php in the process.php file, add the following statement as the first statement in the process.php file:
<?php include 'database.php'?>
      • Here, include keyword does the work of linking the two files.
      • The file name is given just database.php because both files process.php and database.php are in the same folder; if they were in different folders, whole path of database.php file would have been specified.
      • With this we are now successfully connected to the database.
    1. Now it’s time to write the insert query to insert the data accepted in the Add Employee form.
      • So write the following insert query in the process.php file below the variables created previously:
mysqli_query($connect,"insert into     employees(first_name,last_name,department,email) values('$first_name','$last_name','$department','$email')");
      • Here, the variables used in the parenthesis after values are enclosed with single quotes because they are strings and strings should be enclosed into quotes.
    1. After writing the query, just put some values in the form as shown below:

 

inserting_after_query_is written
fig 7

      • Now click on the Add Employee button, you will get the next page.

 

output_after_insertion
fig 8

      • Here, you see no confirmation as your data is inserted or not.
      • In this case you need to open the database and get it confirmed.
      • Now open the employees table in company database and see if Heather Smith has been added or not.
      • It is added successfully and is shown below:

 

employees_table_with_record
fig 9

    1. The record has been inserted successfully in the employees table of company database. Hence now our only requirement is that we should get a notification if our data is successfully inserted or not after executing the query.
      • So write the following code in process.php file.
if(mysqli_affected_rows($connect)>0)
{
	echo '<p>Employee Added !</p>'
	echo '<a href="index.php">GO BACK</a>';
}
else
{
	echo 'Employee NOT added.';
	echo 'mysqli_error($connect)';
}
      • Here, the statement if(mysqli_affected_rows($connect)>0) tells us that the affected rows are more than zero that is something happened in the database, then in this situation we want to display a message Employee Added! and a hyperlink GO BACK.
      • And if the condition is not matched then a message Employee NOT added is displayed and the mysqli error message is also displayed.
      • Now enter another record in the form as shown below:

 

adding_another_record
fig 10

      • Now click on Add Employee button, it will take you to page process.php as shown below:

 

record_added_successfully
fig 11

    • This page shows that record has been added successfully. The GO BACK link takes you to the Add Employee form again.
    • If any error occurs while inserting, you will get an error.

 

Thus we finished inserting data using HTML form as the design part and PHP as the logic into MYSQL database in this PHP, MYSQL and HTML forms tutorial.

7 COMMENTS

  1. I appreciate you for writing
    a remarkably superb blog post. Most people who actually came to this great
    site should have discovered this article literally beneficial.
    I should say that you actually have done wonderful job with this and expect to check out even more great things
    from you. I already have you bookmarked to check out blogs you post.

  2. If some one wishes to be updated with newest technologies then he must
    be visit this site and be up to date every day.

  3. Eu cada vez passou minha meia hora para ler isto site do artigos ou
    clientes todos os dias junto com um caneca café.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -