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.
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>
<?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."' ");
}
?>
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.
<?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>