DEV Community

Gihan Vimukthi
Gihan Vimukthi

Posted on

Save HTML Form Data to a MySQL Database using PHP

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.

<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>
Enter fullscreen mode Exit fullscreen mode

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";
?>
Enter fullscreen mode Exit fullscreen mode

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

?>
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (2)

Collapse
 
abhixsh profile image
Abishek Haththakage

Great article.

Collapse
 
gixa789 profile image
Gihan Vimukthi

Thank You!