How to insert HTML form data into MySQL database using PHP


In this tutorial, we will learn how to insert HTML form data into the MySQL database using PHP. we need to know the basic overview of some superglobal variables in PHP. There are some variables, we can access from anywhere in the PHP script that is called superglobal variables. Some of them are defined as follows—-

1. $_SERVER: It is a global variable that holds information about headers, paths, host address, script locations, etc. such as
    . $_SERVER[‘PHP_SELF’] = Returns the filename of the currently executing script.
    . $_SERVER[‘SERVER_ADDR’] = Returns the IP address of the host server.
    . $_SERVER[‘SERVER_NAME’] = Returns the name of the host server such as www.ndtv.com

    . $_SERVER[‘REQUEST_METHOD’] = Returns the request method used to access the page.

 2. $_REQUEST: It is a superglobal variable that collects data from a form after clicking the submit button.

 3. $_POST: It is a global variable that is used to send form data to the server. Data sent from a form with $_POST method is invisible to others. POST method is used to send sensitive information like username and password etc.

 4. $_GET: It is a global variable that is used to send form data to the server. Data sent from a form with $_GET method is visible to others via URL. It is used for sending non-sensitive data.

Also read, Introduction to PHP and how it works

How to echo form data after submitting in PHP

<html>
<body>

<form method=”post” action=”<?php echo $_SERVER[‘PHP_SELF’];?>”>
Name: <input type=”text” name=”username”>
<input type=”submit” name=”save” value=”submit”>
</form>

<?php
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
// collect value of input field
$username = $_REQUEST[‘username’];
if (empty($username)) {
echo “Username is empty”;
} else {
echo $username;
}
}
?>
</body>
</html>

or

<html>
<body>
<form method=”post” action=””>
Name: <input type=”text” name=”username”>
<input type=”submit” name=”save” value=”submit”>
</form>
</body>
</html>

<?php
if (isset($_POST[‘save’]) //here ‘save’ is the name attribute of the button field
{
// collect value of input field
$username = $_POST[‘username’];//here username is the field name of the input type element

echo $username;

}
?>

In the example above a form is given with an input field and a submit button. When a user clicks the submit button, the form data is sent to the file specified in the action attribute of the <form> tag to process the data.

Here we have used the current file for the action of the data with $_SERVER[‘PHP_SELF’] or we can leave the action attribute blank. If we want then we can use a separate PHP file for the action attribute. Then, we can use the super global variable $_REQUEST to collect the value of the input field or we can use $_POST to retrieve the form data from an input field.

How to insert HTML form data into MySQL database using PHP

How to insert HTML form data into MySQL database using PHP

Insert HTML Form Data into Mysql database using PHP and display it in a table 

1. Create the database in PHPmyadmin with collation “utfmb4-unicode-ci”.

2. Create a table in the database. Here I am using a table named ‘users’ which contains five fields such as “id”,”username”,”phone_no”,”email”,”password”.

  DDL Information of the table:
————————————–
CREATE TABLE `users` (
             `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
             `username` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
             `phone_no` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
             `email` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
             `password` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
              PRIMARY KEY (`id`)
              ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Now, we will do the submission with simple form validation in PHP

Also read, Basic overview of PHP variables and data Types

COMPLETE CODE:-
————————–

connect.php

&lt;?php
$servername='localhost';
$username="root";
$password="";
try
{
	$con=new PDO("mysql:host=$servername;dbname=database name",$username,$password);
	$con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
	//echo 'connected';
}
catch(PDOException $e)
{
	echo '&lt;br>'.$e->getMessage();
}
	
?>
&lt;?php
include('connect.php');
//insert data into database
$username_err=$phone_err=$email_err=$password_err='';
if(isset($_POST['save'])){
//inserting form data with validation
			if(empty($_POST['username'])){
				$username_err = 'Username is required';
			}
			else{
				$username = $_POST['username'];
				//check username
				if(strlen($username)&lt;4 || strlen($username)>6){
					$username_err="Username should be 4 to 6 characters long";	
				}	
			}
			if(empty($_POST['phone_no'])){
				$phone_err = 'Phone No is required';
			}
			else{
				$phone_no = $_POST['phone_no'];
				if(!is_numeric($phone_no)){
					$phone_err = "Phone No should be numeric";
				}
				elseif(strlen($phone_no)>10 || strlen($phone_no)&lt;10){
					$phone_err = "Can not be greater than 10 digits or less than 10 digits!";
				}
			}
			if(empty($_POST['email'])){
				$email_err = 'Email is required';
			}
			else{
				$email = $_POST['email'];
				//check email
				if (!filter_var($email, FILTER_VALIDATE_EMAIL))  
				{
					$email_err = "Invalid email format"; 
				}
			else
				{
					$stmt=$con->prepare("select email from `users` where email='$email'");
					$stmt->execute();
					$rows1 =$stmt->fetch(PDO::FETCH_ASSOC);
					if($rows1!==false)
					{
						$email_err ='This email already exist....please try another';
					}
				}
			}
			if(empty($_POST['password'])){
				$password_err = 'Password is required';
			}
			else{
				$password = $_POST['password'];
				//validate PASSWORD
				if(!preg_match("((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})",$password)){
				
				$password_err="Password should contain uppercase and lowercase letters with mix of special characters and digits and at least 6 characters long";
				}
			}					
	if($username_err=='' &amp;&amp; $phone_err=='' &amp;&amp; $email_err=='' &amp;&amp; $password_err==''){
		
				$username = $_POST['username'];
				$phone_no = $_POST['phone_no'];
				$email 	  = $_POST['email'];
				$password = $_POST['password'];
		
		$sql="INSERT INTO users(username,phone_no,email,password)VALUES('$username','$phone_no','$email','$password')";
		$stmt=$con->prepare($sql);
		$stmt->execute();
		echo "&lt;script type='text/javascript'>";
		echo "alert('Submitted successfully')";
		echo "&lt;/script>";
	}
	/*echo "&lt;script type='text/javascript'>";
	echo "alert('Submitted successfully'.$username)";
	echo "&lt;/script>";*/
	
}
//Display the output from the database
	$stmt1=$con->prepare("SELECT * FROM users order by id asc");
	$stmt1->execute();
	$rows =$stmt1->fetchAll(PDO::FETCH_ASSOC);
//Edit the table data
if(isset($_GET['edit'])){
	$edit_id = $_GET['edit'];
	$stmt2=$con->prepare("SELECT * FROM users where id='$edit_id'");
	$stmt2->execute();
	$edit_details =$stmt2->fetch(PDO::FETCH_ASSOC);
	}
//update the data
	if(isset($_POST['update']))
    {
    	
		$user_name=$_POST['username'];
		$phone_no=$_POST['phone_no'];
		$email=$_POST['email'];
		$password=$_POST['password'];
		$stmt=$con->prepare("update users set username='$user_name',phone_no='$phone_no',email='$email',password='$password' where id='$edit_id'");
		$stmt->execute();
		echo "&lt;script type='text/javascript'>";
		echo "alert('Record updated successfully')";
		echo "&lt;/script>";
		echo "&lt;script type='text/javascript'>";
		echo "window.location='formsubmit.php'";
		echo "&lt;/script>";
		
	}
//delete the data
if(isset($_GET['delete'])){
	$delete_id = $_GET['delete'];
	$stmt3=$con->prepare("delete from users where id='$delete_id'");
	$stmt3->execute();
	echo "&lt;script type='text/javascript'>";
		echo "alert('Record deleted successfully')";
		echo "&lt;/script>";
		echo "&lt;script type='text/javascript'>";
		echo "window.location='formsubmit.php'";
		echo "&lt;/script>";
	}	

?>
&lt;html>
&lt;head>
&lt;title>Form Submission&lt;/title>
&lt;link rel="stylesheet" href="bootstrap.css" crossorigin="anonymous">
&lt;!-- Optional theme -->
&lt;link rel="stylesheet" href="bootstrap-theme.css" crossorigin="anonymous">

&lt;style>
.container{
	width:50%;
	height:30%;
	padding:20px;
	
}


&lt;/style>
&lt;/head>
&lt;body>
	&lt;div class="container">
	&lt;div class="panel panel-primary">
	&lt;div class="panel-heading">Add New Users&lt;/div>
    &lt;div class="panel-body">
		&lt;form action="" method="post">
			&lt;div class="row">
				&lt;div class="col-sm-6">
					&lt;div class="form-group">
					    &lt;label for="username">Username:&lt;/label>
					    &lt;input type="text" value="&lt;?php echo isset($_POST["username"]) ? $_POST["username"] : '';?>" class="form-control" id="user" name="username">
					    &lt;span class="error" style="color: #ff0000">&lt;?php echo $username_err;?>*&lt;/span>
					&lt;/div>
				&lt;/div>
				&lt;div class="col-sm-6">
					&lt;div class="form-group">
					    &lt;label for="phone_no">Phone No:&lt;/label>
					    &lt;input type="text" value="&lt;?php echo isset($_POST["phone_no"]) ? $_POST["phone_no"] : '';?>" class="form-control" id="phone" name="phone_no">
					    &lt;span class="error" style="color: #ff0000">&lt;?php echo $phone_err;?>*&lt;/span>
					&lt;/div>
				&lt;/div>
			&lt;/div>
			&lt;div class="row">
				&lt;div class="col-sm-6">
					&lt;div class="form-group">
					    &lt;label for="Email">Email:&lt;/label>
					    &lt;input type="email" value="&lt;?php echo isset($_POST["email"]) ? $_POST["email"] : '';?>" class="form-control" id="email" name="email">
					    &lt;span class="error" style="color: #ff0000">&lt;?php echo $email_err;?>*&lt;/span>
					&lt;/div>
				&lt;/div>
				&lt;div class="col-sm-6">
					&lt;div class="form-group">
					    &lt;label for="Password">Password:&lt;/label>
					    &lt;input type="password" value="&lt;?php echo isset($_POST["password"]) ? $_POST["password"] : '';?>" class="form-control" id="pass" name="password">
					    &lt;span class="error" style="color: #ff0000">&lt;?php echo $password_err;?>*&lt;/span>
					&lt;/div>
				&lt;/div>
			&lt;/div>
			  &lt;button type="submit" class="btn btn-primary" name="save">Submit&lt;/button>
		&lt;/form>
	&lt;/div>
&lt;/div>
		&lt;br/>
&lt;div class="panel panel-info">
	&lt;div class="panel-heading">User List&lt;/div>
		&lt;table class="table table-bordered">
			&lt;thead>
			      &lt;tr>
			      	&lt;th>ID&lt;/th>
			        &lt;th>Username&lt;/th>
			        &lt;th>Phone No&lt;/th>
			        &lt;th>Email&lt;/th>
			        &lt;th>Password&lt;/th>
			        &lt;th>&lt;/th>
			      &lt;/tr>
			&lt;/thead>
			&lt;tbody>
			&lt;?php
			if(!$rows){
				echo '&lt;tr>
						&lt;td colspan="4">No data available.&lt;/td>
					 &lt;/tr>';
			}
			else{
				foreach($rows as $row)
				{
					?>
					&lt;tr>
							&lt;td>&lt;?php echo $row['id'];?>&lt;/td>
					        &lt;td>&lt;?php echo $row['username'];?>&lt;/td>
					        &lt;td>&lt;?php echo $row['phone_no'];?>&lt;/td>
					        &lt;td>&lt;?php echo $row['email'];?>&lt;/td>
					        &lt;td>&lt;?php echo $row['password'];?>&lt;/td>
					        &lt;td>&lt;a class="btn btn-info" onclick="return confirm('Are you sure?')" href="formsubmit.php?edit=&lt;?php echo $row['id']?>">Edit&lt;/a>
					        &lt;a class="btn btn-danger" onclick="return confirm('Are you sure?')" href="formsubmit.php?delete=&lt;?php echo $row['id']?>">Delete&lt;/a>&lt;/td>
					&lt;/tr>
					&lt;?php
				}
			}
			
			?>
			      
			&lt;/tbody>
  		&lt;/table>
	&lt;/div>
	&lt;!--Edit users list-->
&lt;?php
	if(isset($_GET['edit'])){
		
		?>
		&lt;div class="panel panel-success">
	&lt;div class="panel-heading">Edit Users Info&lt;/div>
    &lt;div class="panel-body">
		&lt;form action="" method="post">
			&lt;div class="row">
				&lt;div class="col-sm-6">
					&lt;div class="form-group">
					    &lt;label for="username">Username:&lt;/label>
					    &lt;input type="text" class="form-control" id="user" value="&lt;?php echo $edit_details['username']?>" name="username" required="">
					&lt;/div>
				&lt;/div>
				&lt;div class="col-sm-6">
					&lt;div class="form-group">
					    &lt;label for="phone_no">Phone No:&lt;/label>
					    &lt;input type="text" value="&lt;?php echo $edit_details['phone_no']?>" class="form-control" id="phone" name="phone_no" required="">
					&lt;/div>
				&lt;/div>
			&lt;/div>
			&lt;div class="row">
				&lt;div class="col-sm-6">
					&lt;div class="form-group">
					    &lt;label for="Email">Email:&lt;/label>
					    &lt;input type="email" value="&lt;?php echo $edit_details['email']?>" class="form-control" id="email" name="email" required="">
					&lt;/div>
				&lt;/div>
				&lt;div class="col-sm-6">
					&lt;div class="form-group">
					    &lt;label for="Password">Password:&lt;/label>
					    &lt;input type="password" value="&lt;?php echo $edit_details['password']?>" class="form-control" id="pass" name="password" required="">
					&lt;/div>
				&lt;/div>
			&lt;/div>
			  &lt;button type="submit" class="btn btn-default" name="update">Submit&lt;/button>
		&lt;/form>
	&lt;/div>
&lt;/div>
		&lt;?php
	}
	
?>
&lt;/div>
&lt;script src="jquery-3.2.1.min.js">&lt;/script>
&lt;script src="bootstrap.min.js">&lt;/script>

&lt;/body>
&lt;/html>

NOTE*

Download the bootstrap CSS and js files from google and include the path of the files in the href attribute of the link tag and src attribute of the script tag respectively.

CONCLUSION:- I hope this article will help you to understand how to insert HTML form data into the MySQL database. If you have any doubt then please leave your comment below.


1 thought on “How to insert HTML form data into MySQL database using PHP”

Leave a Comment

ceri188

ceri188

ceri188

KUPU178

HOKI311

RATU311

KUPU178

RATU311

RATU311

kupu178

kupu178

HOKI311

togel

kupu178

ratu311

mix parlay

ceri188

slot online

kupu178

KUPU178

RATU311

THOR311

THOR311

THOR311

THOR311

KUPU178

KUPU178

KUPU178

RATU311

RATU311

RATU311

kupu178

hoki311

THOR311

hoki311

togel online

kupu178

slot mahjong

ceri188

slot server thailand

ratu311

ceri188

ceri188

RATU311

punjabi virasat

mimcord.com

Centrum Medyczne

www.vrcorporate.in

phbalance.vn

THOR311

KUPU178

daftar slot gacor

hoki311

togel hongkong

kupu178

slot mahjong

ratu311

slot gacor

kupu178

kupu178

ceri188

kupu178

ceri188

THOR311

KUPU178

KUPU178

KUPU178

RATU311

kupu178

RATU311

RATU311

RATU311

KUPU178

KUPU178

RATU311

RATU311

slot online

kupu178

thor311

thor311

kupu178

kupu178

RATU311

KUPU178

THOR311

THOR311

THOR311

KUPU178

slot mahjong ways

hoki311

slot gacor

ceri188

ratu311

kupu178

Casino Baccarat Online

kupu178

kupu178

ceri188

ceri188

THOR311

THOR311

RATU311

toto macau

KUPU178

slot gacor

HOKI311

sabung ayam online

RATU311

SLOT LUCKY NEKO

CERI188

Slot Gacor

KUPU178

RATU311

RATU311

Link Spaceman

CERI188

Slot Gacor Online

THOR311

Mahjong ways

KUPU178

THOR311

THOR311

Live Casino

HOKI311

CERI188

CERI188

THOR311

THOR311

THOR311

RATU311

RATU311

RATU311

RATU311

RATU311

RATU311

RATU311

RATU311

KUPU178

KUPU178

CERI188

HOKI311 SLOT

TOTO TOGEL TOKYO

CERI188

CERI188 SITE

CERI188

RATU311

RATU311

RATU311

RATU311

RATU311

KUPU178

Toto Togel

KUPU178

Slot Mahjong

CERI188

CERI188

CERI188

Slot Sweet Bonanza 2500

KUPU178

SLOT ONLINE

RATU311

RATU311

RATU311

RATU311

RATU311

RATU311

KUPU178

KUPU178 X SLOT777

judi bola online

THOR311

KUPU178 10 GAME SLOT TERBAIK

KUPU178

KUPU178 SLOT TERPERCAYA

KUPU178 TOGEL

TOTO 4D MACAU

KUPU178

SITUS BOLA

CERI188

KUPU178

RATU311

THOR311

THOR311

HOKI311

KUPU178

RATU311

THOR311

CERI188

Slot Mahjong Ways

KUPU178

CERI188

Slot Online Resmi

KUPU178

RATU311 SLOT ONLINE

KUPU178

KUPU178: Link Akses Resmi

KUPU178: Strategi Menang Di Game Live Casino

KUPU178

KUPU178: Minimal 200 Rupiah

Slot Gacor Online

KUPU178

Mix Parlay

CERI188

CERI188

THOR311

THOR311

THOR311

THOR311

THOR311

KUPU178

Slot Thailand

CERI188

CERI188

THOR311 RTP

RATU311

RATU311

RATU311

CERI188

KUPU178 TOTO SLOT

CERI188 TOTO Singapore

THOR311

KUPU178

KUPU178

RATU311

CERI188

RATU311: Alternatif karnpuracollege

RATU311

RATU311

Thor311 Terbaru

THOR311 MAHJONG

RATU311: BONUS SABUNG AYAM

CERI188: Masuk Akun Slot Super Cepat

THOR311 PRO

CERI188

CERI188

CERI188

THOR311

HOKI311

HOKI311

RATU311

HOKI311

KUPU178

RATU311

RATU311

RATU311

RATU311

THOR311

CERI188

CERI188

RATU311

RATU311

RATU311

RATU311

Game Thor311

HOKI311

HOKI311

RATU311

HOKI311

HOKI311

THOR311

RATU311 NONTON BOLA

RATU311

HOKI311 Link QRIS EWALLET

RATU311

HOKI311 Link Apk Resmi

CERI188

RATU311 judi bola

KUPU178

situs judi bola

HOKI311

RATU311

THOR311

HOKI311

KUPU178

kupu178 link alternatif

kupu178 slot

kupu178 daftar

kupu178 login

link daftar kupu178

judi bola

RATU311

link alternatif RATU311

Link daftar RATU311

link login RATU311

RATU311

KUPU178

KUPU178

RATU311

RATU311

KUPU178

THOR311

slot thailand

judi bola

KUPU178

slot gacor

slot gacor

yakuza303

slot gacor

RATU311

THOR311