Save HTML Form Data to a MySQL Database using PHP

GihanVimukthi
2 min readFeb 10, 2023

--

When We building websites we need to do different work related to our thoughts and requirements. In this small article I like to talk about saving html form data or user input data to a mysql database using php.

Firstly you need to create and arrange your user data input web page by using html and css. Here I am using only two user inputs and a submit button to submit data.

Then open the form tag to connect the new php file by pressing the Submit button like the code.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="newproject.css">
<title>New Project</title>

</head>
<body>
<h3>EXAMPLE PROJECT</h3><br><br>
<form action="process-exampleform.php"method="POST">

<div class="firstname">
<label>First_Name</label><br>
<input type="text" id="Code" name="First_Name">
</div>
<div class="lastname">
<label>Last_Name</label><br>
<input type="text" id="Code" name="Last_Name">
</div>
<button>Submit</button>
</form>
</body>
</html>

After that we need to create another php. File to process and transfer data to sql table. In this I create process-exampleform.php file to explain this.

In php code you need to get inputs from the webpage by POST method.

<?php
$First_Name=$_POST["First_Name"];
$Last_Name=$_POST["Last_Name"];

$host="localhost";
$dbname="database name";
$username="username";
$password="";

$conn=mysqli_connect($host,$username,$password,$dbname);
if(mysqli_connect_errno()){
die("Connection Error:".mysqli_connect_error());
}


$sql="INSERT INTO Details(First_Name,Last_Name)
VALUES(?,?)";

$stmt=mysqli_stmt_init($conn);

if(! mysqli_stmt_prepare($stmt,$sql)){
die(mysqli_error($conn));
}

mysqli_stmt_bind_param($stmt,"ss",
$First_Name,
$Last_Name,
);

mysqli_stmt_execute($stmt);
echo"Record saved";
?>

Then you need to create another php. File to connect webpage and example php file.

<?php
//connection for the database to html
$con=mysqli_connect("localhost","user name","password","database");

if(!$con){
die("Connection error");
}

?>

Then you need to create another php. File to connect webpage and example php file.

<?php
//connection for the database to html
$con=mysqli_connect("localhost","user name","password","database");

if(!$con){
die("Connection error");
}

?>

After all of that you need to create a database and need to create a sql table and submit data .

To know about creating a database and table read the next article .

Thank You!

--

--

GihanVimukthi
0 Followers

Welcome to My Profile. I appreciate your come.