Database insert data into table using form input fields


php Database insert data into table using form input fields PHP And Forms

How to insert the data into the database table using form text field ?

To insert the data from input fields we first create a form with method='post'. We are using the post method because we want to submit the input fields to the PHP code as post data. Below examples will make better understanding. We want to insert the data into the below database table.

First we will create an html design structure with form input fields.

HTML Form with different input fields

We will create four following input fields. 1- first_name 2- last_name 3- username 4- password

<html> <head> <title>Insert Data into Database table using forms</title> </head> <body> <form method="post"> First Name: <input type="text" name="first_name"> <br> Last Name: <input type="text" name="last_name"> <br> Username: <input type="text" name="username"> <br> Password: <input type="password" name="password"> <br> <input type="submit" name="submit"> <br> </form> </body> </html>

HTML Sample Page:

First Name:
Last Name:
Username:
Password :

Important Note ! We will use the <input> attribute ' name in PHP code ' e.g name="first_name".

PHP code to insert the data using form input fields

<?php $conn = mysqli_connect('localhost', 'root', '', 'myfirstdatabase'); if(isset($_POST['submit'])){ //if user submit on submit button. $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; $username = $_POST['username']; $password = $_POST['password']; mysqli_query($conn,"INSERT INTO users SET first_name='".$first_name."',last_name='".$last_name."', username='".$username."',password='".$password."' "); } ?>

Where to write the PHP code ?

We can write the PHP code into the separate file e.g insert.php but we have to write the action address page link in the <form> attribute like below.

<form method="post" action="insert.php"> However we can write the PHP and HTML code in a single file.

Full HTML and PHP Source Code for inserting data into database table

<?php $conn = mysqli_connect('localhost', 'root', '', 'myfirstdatabase'); if(isset($_POST['submit'])){ //if user submit on submit button. $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; $username = $_POST['username']; $password = $_POST['password']; mysqli_query($conn,"INSERT INTO users SET first_name='".$first_name."',last_name='".$last_name."', username='".$username."',password='".$password."' "); } ?> <html> <head> <title>Insert Data into Database table using forms</title> </head> <body> <form method="post"> First Name: <input type="text" name="first_name"> <br> Last Name: <input type="text" name="last_name"> <br> Username: <input type="text" name="username"> <br> Password: <input type="password" name="password"> <br> <input type="submit" name="submit"> <br> </form> </body> </html>
php PHP And Forms Chapter Next »