🌐
DEV Community
dev.to › anthonys1760 › how-to-insert-form-data-into-a-database-using-html-php-2e8
How to Insert Form Data into a Database Using HTML & PHP - DEV Community
August 22, 2022 - It is a way to store and retrieve data from a computer or server. Xampp stands for "Extended Apache MySQL Platform". It is a free and open-source software that allows you to run a database server on your computer. It utilizes MySQL, Apache, PHP and Perl as its database engine, and it is free to use. <?php // Set your connection variables $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database_name"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " .
🌐
Medium
medium.com › @gihan2000v › save-html-form-data-to-a-mysql-database-using-php-3d48742a1451
Save HTML Form Data to a MySQL Database using PHP | by GihanVimukthi | Medium
February 10, 2023 - <?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 .
Discussions

Populate HTML loaded form from PHP/MySQL - Stack Overflow
I have read many posts here and on other sites where they explain how to read a MySQL database and show the data on an HTML form. The problem with all that information is that the examples build the More on stackoverflow.com
🌐 stackoverflow.com
Taking mySQL database input from HTML form with PHP - Stack Overflow
I'm trying to take in data from a webpage with a HTML form and PHP to my mySQL Database. It connects just fine on both pages but I get an error when I try to submit from the form. It will take in d... More on stackoverflow.com
🌐 stackoverflow.com
How to make a PHP/HTML form with MySQL? - Stack Overflow
I have a HTML form that stores the information on a MySQL database. It works! But I want an only file that do all with PHP extension. I filled the database when clicking on the button but turn to d... More on stackoverflow.com
🌐 stackoverflow.com
Build a HTML form to insert data in a database in PHP MySQLi - software engineering - Discuss Career & Computing - OpenGenus
In this article, we are going to see how a form is made and how the details entered by the user are stored in a database. As we code along, we are going to create a webpage which has a form and we will store the entries in a table in a database. You will learn: basic ideas like database, table, ... More on discourse.opengenus.org
🌐 discourse.opengenus.org
1
August 13, 2019
🌐
GeeksforGeeks
geeksforgeeks.org › php › how-to-insert-form-data-into-database-using-php
How to Insert Form Data into Database using PHP ? - GeeksforGeeks
July 23, 2025 - ... Storing User Input into a MySQL database using PHP is a foundational step in developing dynamic and data-driven web applications. Use HTML <form> elements to collect user data and submit it to PHP for processing.
🌐
C# Corner
c-sharpcorner.com › UploadFile › 52bd60 › create-an-html-form-and-insert-data-into-database162
Create An HTML Form And Insert Data Into The Database Using PHP
November 20, 2023 - This article shows how we can create a SIGN UP form and store the entered data into our database (mysql) using PHP.
🌐
LinkedIn
linkedin.com › all › engineering › programming
How can you use HTML forms to store data in a database?
January 28, 2024 - To insert data into a database, you need to write a SQL query that specifies the table name, the column names, and the values to be inserted. You can use the mysqli_query function in PHP to execute the query, or use the PDO::exec method to run ...
🌐
Eli the Computer Guy
elithecomputerguy.com › 2019 › 12 › mysql-insert-records-with-html-form-and-php
MySQL – INSERT Records with HTML Form and PHP – Eli the Computer Guy
<?php $name = $_POST['name']; $age = $_POST['age']; $gender = $_POST['gender']; $servername = "localhost"; $username = "bob"; $password = "123456"; $db = "classDB"; $conn = new mysqli($servername, $username, $password, $db); if ($conn->connect_error){ die("Connection failed: ". $conn->connect_error); } $sql = "insert into students(name,age,gender) values('$name','$age','$gender')"; if ($conn->query($sql) === TRUE) { echo "ADDED: ".$name.", ".$age.", ".$gender; } else { echo "Error: ".$sql."<br>".$conn->error; } $conn->close(); ?> ... PHP is great for being able to easily create web apps that work.
🌐
Raghwendra
raghwendra.com › home › how to connect html to database with mysql using php? an example
How to connect HTML to database with MySQL using PHP? example
June 25, 2023 - Check your database port and put as a fifth parameter in the connection line. $con = mysqli_connect(“localhost”, “root”, “”, “db_contact”,”3308″); Will the above code work for HTML tables.
Top answer
1 of 1
1

Answer as per OP :

  • Create a php script to receive http requests and fetch data from the database

    1. Create a php script called api.php on your server
    2. Copy and paste the example below and save it:

.

<?php 
  //--------------------------------------------------------------------------
  // Example php script for fetching data from mysql database
  //--------------------------------------------------------------------------
  $host = "localhost";
  $user = "root";
  $pass = "root";

  $databaseName = "ajax01";
  $tableName = "variables";

  //--------------------------------------------------------------------------
  // 1) Connect to mysql database
  //--------------------------------------------------------------------------
  include 'DB.php';
  $con = mysql_connect($host,$user,$pass);
  $dbs = mysql_select_db($databaseName, $con);

  //--------------------------------------------------------------------------
  // 2) Query database for data
  //--------------------------------------------------------------------------
  $result = mysql_query("SELECT * FROM $tableName");          //query
  $array = mysql_fetch_row($result);                          //fetch result    

  //--------------------------------------------------------------------------
  // 3) echo result as json 
  //--------------------------------------------------------------------------
  echo json_encode($array);

?>
  • Create a client script to fetch data from the API script using JQuery AJAX

    1. Create a html script called client.php in the same directory with the following content in it:

.

<!---------------------------------------------------------------------------
Example client script for JQUERY:AJAX -> PHP:MYSQL example
---------------------------------------------------------------------------->

<html>
  <head>
    <script language="javascript" type="text/javascript" src="jquery.js"></script>
  </head>
  <body>

  <!-------------------------------------------------------------------------
  1) Create some html content that can be accessed by jquery
  -------------------------------------------------------------------------->
  <h2> Client example </h2>
  <h3>Output: </h3>
  <div id="output">this element will be accessed by jquery and this text replaced</div>

  <script id="source" language="javascript" type="text/javascript">

  $(function () 
  {
    //-----------------------------------------------------------------------
    // 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
    //-----------------------------------------------------------------------
    $.ajax({                                      
      url: 'api.php',                  //the script to call to get data          
      data: "",                        //you can insert url argumnets here to pass to api.php
                                       //for example "id=5&parent=6"
      dataType: 'json',                //data format      
      success: function(data)          //on recieve of reply
      {
        var id = data[0];              //get id
        var vname = data[1];           //get name
        //--------------------------------------------------------------------
        // 3) Update html content
        //--------------------------------------------------------------------
        $('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
        //recommend reading up on jquery selectors they are awesome 
        // http://api.jquery.com/category/selectors/
      } 
    });
  }); 

  </script>
  </body>
</html>

Answer put up only for reference, it is from here.

🌐
Sanwebe
sanwebe.com › html-css › php › snippets › creating simple form using php and mysql
Creating Simple Form using PHP and MySql – Sanwebe
July 1, 2025 - Now, update process.php to connect to MySQL and store the data using prepared statements for security. 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 · &lt;?php // process.php if ($_SERVER["REQUEST_METHOD"] == "POST") { // MySQL credentials $mysql_host = "localhost"; $mysql_username = "your_username"; // Replace with your MySQL username $mysql_password = "your_password"; // Replace with your MySQL password $mysql_database = "your_database"; // Replace with your database name $u_name = filter_input(INPUT_POST, "user_name", FILTER_SANITIZE_STRING); $u_email
Find elsewhere
🌐
Brainly
brainly.com › computers and technology › high school › how to connect an html form to a mysql database (w3schools)
[FREE] How to connect an HTML form to a MySQL database (W3Schools) - brainly.com
November 27, 2023 - In the PHP script, establish a connection to MySQL with appropriate credentials, retrieve form data using the $_POST variable, and execute an SQL INSERT statement to add data to the designated table.
🌐
Scribd
scribd.com › document › 487792746 › form
Create An HTML Form and Insert Data Into The Database Using PHP | PDF | Php | Hypertext
Key elements include designing the HTML form, linking a CSS stylesheet, writing PHP code to connect to MySQL and select a database, and creating a database table to store submitted form records.Read moreDownload
🌐
Educative
educative.io › answers › how-to-connect-an-html-form-to-a-mysql-database-in-php
How to connect an HTML form to a MySQL database in PHP
This ensures that the server, MySQL, and Apache is running. Otherwise, we might get an error. Next, we'll create the PHP file. The sample code, along with the explanation, is given below: ... Line 2: We'll use the $_POST as connection type to get HTML form entries. Lines 4–6: We define the fields here. The square brackets contain the values of the name attribute in the input labels of the HTML code. Finally, we'll connect our HTML form to the database ...
🌐
YouTube
youtube.com › john morris
How to Create an HTML Form That Stores Data in a MySQL Database Using PHP Part 4 of 4 - YouTube
Get the updated source code here: https://myjohn.us/formsMake sure to watch the UPDATED version of this tutorial here: https://www.youtube.com/watch?v=BmHLvU...
Published   October 11, 2010
Views   107K
Top answer
1 of 2
2

You are getting blank options AFTER each option with an expected value because you have failed to write a closing option tag. / needs to be written into the second option tag like this:

while ($row = mysqli_fetch_array($result)) {
    echo "<option>{$row['CourseID']}</option>";
}

The option tags still render even if you don't properly close them. In this case, the error presents itself by generating twice the desired tags.

I recommend that you use MYSQLI_ASSOC as the second parameter of your mysqli_fetch_array call or more conveniently: mysqli_fetch_assoc

In fact, because $result is iterable, you can write:

foreach ($result as $row) {
    echo "<option>{$row['CourseID']}</option>";
}

About using extract($_POST)...

I have never once found a good reason to use extract in one of my scripts. Not once. Furthermore, the php manual has a specific Warning stating:

Warning Do not use extract() on untrusted data, like user input (e.g. $_GET, $_FILES).

There are more warning down the page, but you effectly baked insecurity into your code by calling extract on user supplied data. DON'T EVER DO THIS, THERE IS NO GOOD REASON TO DO IT.

Here is a decent page that speaks about accessing submitted data: PHP Pass variable to next page

Specifically, this is how you access the expected superglobal data:

$name = $_POST['name'];
$testsentence = $_POST['testsentence'];
$courseid = $_POST['course'];

You must never write unfiltered, unsanitized user supplied data directly into your mysql query, it leads to query instability at best and insecurity at worst.

You must use a prepared statement with placeholders and bound variables on your INSERT query. There are thousands of examples of how to do this process on Stackoverflow, please research until it makes sense -- don't tell yourself that you'll do it layer.

2 of 2
-2

Make sure you added extract($_POST) (or something similar) in your PHP code!

You need to extract the parameters from your POST request before using them, otherwise your $name, $testsentence, and $courseid will be undefined.

🌐
Quora
quora.com › How-can-I-build-a-PHP-form-using-a-MySQL-database
How to build a PHP form using a MySQL database - Quora
Answer (1 of 2): Heres the code which i recently used to make form through php, mysql and html. Step 1: Make a simple HTML form as you wish to create as per your requirment. or heres my created form. Code is: [code]
Top answer
1 of 3
1

If i understood good what you are asking, the HTML and the PHP can be on the same page.

Take in mind that the better practice is to put the processnig code in the top of the file.

<?php
if(isset($_POST['button'])){
    $mysqli = mysqli_connect("localhost", "user", "12345", "own_bd");

    if (mysqli_connect_errno()) {
        printf("Problem with connection: %s\n", mysqli_connect_error());
        exit();
    } 
    else {
        $var_name = mysqli_real_escape_string($mysqli, $_POST['name']);
        $var_lst = mysqli_real_escape_string($mysqli, $_POST['lstname']);
        $var_mail = mysqli_real_escape_string($mysqli, $_POST['email']);
        $var_pwd = mysqli_real_escape_string($mysqli, $_POST['password']);
        $var_pwdr = mysqli_real_escape_string($mysqli, $_POST['passwordr']);
        $sql = "INSERT INTO users_tbl (Name,Lastname,Mail,Pwd,PwdR) VALUES ('".$var_name."','".$var_lst."','".$var_mail."','".$var_pwd."','".$var_pwdr."')";
        $res = mysqli_query($mysqli, $sql);

        if ($res === TRUE) {
            echo "User added.";
            exit();
        } 
        else {
            printf("Error: %s\n", mysqli_error($mysqli));
        }

    }
    mysqli_close($mysqli);
}
?>
<html>
  <head></head>
  <body>
    <form id="form" name="form" action="" method="POST">
      <label id="lbluser">Name:</label>
      <input type="text" name="name" id="name" /><br/>
      <label id="lbllastaname">Lastname:</label>
      <input type="text" name="lstname" id="lstname" /><br/>
      <label id="lblmail">E-mail:</label>
      <input type="text" name="email" id="email" /><br/>
      <label id="lblpassword">Password:</label>
      <input type="password" name="password" id="password" /><br/>
      <label id="lblpassword">Repeat password:</label>
      <input type="password" name="passwordr" id="passwordr" /><br/>
      <button type="submit" name="button" value="insert">OK</button>
    </form>
  </body>
</html>
2 of 3
0

After i understand that you are looking for a HTML and PHP code both in the same file and Answer from Bob0t. The only thing which you might need to change here is isset($_POST['button']) to isset($_POST['BtnSubmit']) and change the <button type=”submit” name=”button” value=”insert”> to <button type=”submit” value=”BtnSubmit”>

<?php
if(isset($_POST['BtnSubmit'])){
    $mysqli = mysqli_connect("localhost", "user", "12345", "own_bd");

    if (mysqli_connect_errno()) {
        printf("Problem with connection: %s\n", mysqli_connect_error());
        exit();
    } 
    else {
        $var_name = mysqli_real_escape_string($mysqli, $_POST['name']);
        $var_lst = mysqli_real_escape_string($mysqli, $_POST['lstname']);
        $var_mail = mysqli_real_escape_string($mysqli, $_POST['email']);
        $var_pwd = mysqli_real_escape_string($mysqli, $_POST['password']);
        $var_pwdr = mysqli_real_escape_string($mysqli, $_POST['passwordr']);
        $sql = "INSERT INTO users_tbl (Name,Lastname,Mail,Pwd,PwdR) VALUES ('".$var_name."','".$var_lst."','".$var_mail."','".$var_pwd."','".$var_pwdr."')";
        $res = mysqli_query($mysqli, $sql);

        if ($res === TRUE) {
            echo "User added.";
            exit();
        } 
        else {
            printf("Error: %s\n", mysqli_error($mysqli));
        }

    }
    mysqli_close($mysqli);
}
?>
<html>
  <head></head>
  <body>
    <form id="form" name="form" action="" method="POST">
      <label id="lbluser">Name:</label>
      <input type="text" name="name" id="name" /><br/>
      <label id="lbllastaname">Lastname:</label>
      <input type="text" name="lstname" id="lstname" /><br/>
      <label id="lblmail">E-mail:</label>
      <input type="text" name="email" id="email" /><br/>
      <label id="lblpassword">Password:</label>
      <input type="password" name="password" id="password" /><br/>
      <label id="lblpassword">Repeat password:</label>
      <input type="password" name="passwordr" id="passwordr" /><br/>
      <button type=”submit” value=”BtnSubmit”>OK</button>
    </form>
  </body>
</html>
🌐
Techieclues
techieclues.com › articles › inserting-html-form-data-into-a-mysql-database-with-php
Inserting HTML Form Data into a MySQL Database with PHP
October 6, 2023 - In this article, we will learn how to insert form data submitted through an HTML form into a MySQL database using PHP. Follow our step-by-step tutorial, including MySQL query creation, PHP program implementation, and output interpretation. Enhance your web development skills and securely store ...
🌐
Eduonix Blog
blog.eduonix.com › home › 2014 › july › php,mysql and html forms
PHP,MYSQL and HTML Forms
May 27, 2016 - This will store all the values in different respective variables. We have all the values that are to be inserted. So now we need to connect to the database. To connect to the database we need to write the connection code as follows: <?php //create connection $connect=mysqli_connect('localhost','root','12345','company'); //check connection if(mysqli_connect_errno($connect)) { echo 'failed to connect!'; } ?>
🌐
Opengenus
discourse.opengenus.org › software engineering
Build a HTML form to insert data in a database in PHP MySQLi - software engineering - Discuss Career & Computing - OpenGenus
August 13, 2019 - In this article, we are going to see how a form is made and how the details entered by the user are stored in a database. As we code along, we are going to create a webpage which has a form and we will store the entries in a table in a database. You will learn: basic ideas like database, table, primary key post API and insertion in a database table setting up a server, database, connecting your application and inserting data through a form The technology stack used for backend in this arti...