How to connect HTML to database with MySQL using PHP? An example

How to connect HTML to database with MySQL using PHP? An exampleHow to connect HTML to database with MySQL using PHP? An example – This article helps to become a custom PHP developer. You will get complete steps for PHP database connection example program. This article provide you HTML form, DB + Table SQL code, Boostrap 5 with CSS, Form Validation and database connection +  submission code .  In the conclusion step, you will be GIT download link so no need to copy-paste the code.

Tools Required to connect HTML Form with MySQL Database using PHP

First of all, you must be install any XAMPP or WAMP or MAMP kind of software on your laptop or computer. With this software, you will get a local webserver i.e. Apache, PHP language, and MySQL database. The complete code is on Github and the download link is the last of this article.

In this article, my PHP, MySQL example is with database connection in xampp code.

After installation you need to on the Xampp see the image below:
Xampp Apache and MySQL on

After installation of any of these laptop or desktop software you need to check your localhost is working or not. Open your browser and check this URL or http://localhost/ . If this is working it means you have the local webserver activated with PHP/MySQL.

Also, GUI PHPmyAdmin coming for handling CRUD operations i.e. insert(create), update, delete, and select(read) records from tables. This interface is browser-based and very helpful, easy to use for creating and managing phpmyadmin database in table(column, row).

If you have the above installation you can go ahead to start your coding.

If you have not a LAMP stack-based web server then you can do this directly in your hosting space.

If you have any more query then you can comment on this post. We will reply to your query.

Suppose you have a web page to insert contact form field data in your DB. For this you need to follow the following steps:

Step 1: Filter your HTML form requirements for your contact us web page

Suppose you selected the form field Name (text input), Email(email input), Phone (number input), and message (multi-line text). The form submit button also necessary for submitting the form. You will get the complete form in HTML coding in step 3.

Step 2: Create a database and a table in MySQL

Open a web browser (chrome, firefox, edge, etc., ) and type this http://localhost/phpmyadmin/ or for open GUI for managing DB on your computer. See the xampp screen below how it is coming.

Click on the databases link and create your db by the name “db_contact”. See the image below:

After creating your DB you need to create a table by any name I choose “tbl_contact” with the number of field 5. We choose 4 fields on top Name, Email, Phone, and Message. The first column we will keep for maintaining the serial number and in technical terms primary key(unique number of each recor). See the image below

When you will click to go button you will get this screen. Now we need to feed every field information.

See the below image in which I added field information. So for field Name used field Name – fldName, Email – fldEmail, Phone – fldPhone, Message – fldMessage.

Now click on the save button that is on the bottom right of your screen. After saving your table it is created in your database.

You can create your DB and table using the SQL below. You have to copy the following code and paste it into your MySQL GUI  phpmyadmin database or any other GUI or command prompt. At the bottom of the blog, you will get a git download link to download the SQL file.

-- Database: `mydb`

USE `db_contact`;

-- --------------------------------------------------------

-- Table structure for table `tbl_contact`

DROP TABLE IF EXISTS `tbl_contact`;
`id` int(11) NOT NULL,
`fldName` int(50) NOT NULL,
`fldEmail` int(150) NOT NULL,
`fldPhone` varchar(15) NOT NULL,
`fldMessage` text NOT NULL

-- Indexes for dumped tables

-- Indexes for table `tbl_contact`
ALTER TABLE `tbl_contact`

-- AUTO_INCREMENT for dumped tables

-- AUTO_INCREMENT for table `tbl_contact`
ALTER TABLE `tbl_contact`

Step 3: Create HTML form for connecting to database

Now you have to create an HTML form. For this, you need to create a working folder first and then create a web page with the name “contact.html”. If you install xampp your working folder is in folder this “E:\xampp\htdocs”. You can create a new folder “contact” on your localhost working folder. Create a “contact.html” file and paste the following code.

<!DOCTYPE html>
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact Form - PHP/MySQL Demo Code</title>

<legend>Contact Form</legend>
<form name="frmContact" method="post" action="contact.php">
<label for="Name">Name </label>
<input type="text" name="txtName" id="txtName">
<label for="email">Email</label>
<input type="text" name="txtEmail" id="txtEmail">
<label for="phone">Phone</label>
<input type="text" name="txtPhone" id="txtPhone">
<label for="message">Message</label>
<textarea name="txtMessage" id="txtMessage"></textarea>
<input type="submit" name="Submit" id="Submit" value="Submit">

Now your form is ready. You may test it in your localhost link http://localhost/contact/contact.html
In the next step, I will go with creating PHP / MySQL code.

Step 4: Create a PHP page to save data from HTML form to your MySQL database

The contact HTML form action is on “contact.php” page. On this page, we will write code for inserting records into the database.

For storing data in MySQL as records, you have to first connect with the DB. Connecting the code is very simple. The mysql_connect in PHP is deprecated for the latest version therefore I used it here mysqli_connect.

$con = mysqli_connect("localhost","your_localhost_database_user","your_localhost_database_password","your_localhost_database_db");

You need to place value for your localhost username and password. Normally localhost MySQL database username is root and password blank or root. For example, the code is as below

$con = mysqli_connect('localhost', 'root', '',’db_contact’);
The “db_contact” is our database name that we created before.
After connection database you need to take post variable from the form. See the below code
$txtName = $_POST['txtName'];
$txtEmail = $_POST['txtEmail'];
$txtPhone = $_POST['txtPhone'];
$txtMessage = $_POST['txtMessage'];

When you will get the post variable then you need to write the following SQL command.

$sql = "INSERT INTO `tbl_contact` (`Id`, `fldName`, `fldEmail`, `fldPhone`, `fldMessage`) VALUES ('0', '$txtName', '$txtEmail', '$txtPhone', '$txtMessage');"

For fire query over the database, you need to write the following line

$rs = mysqli_query($con, $sql);

Here is PHP code for inserting data into your database from a form.

// database connection code
// $con = mysqli_connect('localhost', 'database_user', 'database_password','database');

$con = mysqli_connect('localhost', 'root', '','db_contact');

// get the post records
$txtName = $_POST['txtName'];
$txtEmail = $_POST['txtEmail'];
$txtPhone = $_POST['txtPhone'];
$txtMessage = $_POST['txtMessage'];

// database insert SQL code
$sql = "INSERT INTO `tbl_contact` (`Id`, `fldName`, `fldEmail`, `fldPhone`, `fldMessage`) VALUES ('0', '$txtName', '$txtEmail', '$txtPhone', '$txtMessage')";

// insert in database 
$rs = mysqli_query($con, $sql);

	echo "Contact Records Inserted";


Step 5:  All done!

Now the coding part is done.  Download code from github

If you would like to check then you can fill the form http://localhost/contact/contact.html and see the result in the database. You may check via phpmyadmin your inserted record.

Why skills as a custom PHP developer?

Php is the most popular server-side programming language. It is used more than 70% in comparison to other website development languages. As a lot of CMS and custom PHP applications developed already on PHP, therefore, it will be a demanding language for the next 5 years.

The worldwide PHP development company is looking for cheap PHP developers in India. Many companies also like to freelance PHP developers in Delhi, London, Bangalore, Mumbai (locally).  If you would like to hire a dedicated developer then you need to skills yourself.


See more answer about PHP script connect to Mysql on Facebook Group

Please join Facebook group for discussion click here
Post your question here with the HASH tag  #connectphpmysql  #connecthtmlmysql  . We will approve and answer your question.

Please view more answer on this hashtag on Facebook Group #connectphpmysql  #connecthtmlmysql




99 responses to “How to connect HTML to database with MySQL using PHP? An example”

  1. Narendar Avatar

    when I enterd credentials on form its not taking the values instead its showing “” Do you want to open contact.php from DESKTOP-8Ca……. & two options :: open or cancel. even after clicking open its not taking the values and not storing them on database..

    1. Raghwendra Avatar

      Narendar, Have you installed any LAMP stack on your computer?

  2. Devanand Avatar

    Thank you very much.
    I successfully added my first data into the database from these instructions.

    1. raghwendra Avatar

      Happy to hear the PHP/MySQL code is working at your laptop.

    2. Samir Avatar

      I follow the steps , but failed to connect DB, i receved a messege(php not found , editd or deleted) )

  3. Ronald Whitelaw Avatar

    RAGHWENDRA – Thank you for the code. I am learning HTML and PHP and want to do a small community database. Learned a lot and it works! My only question is on the configuration of WAMP itself. I downloaded and installed the latest version of wamp and it loads and I get the green icon. I put the 2 contact files, html and php in the www directory. When I go to the www directory and click on the contact.html I enter the data but when it tries to execute the contact.php file it merely displays the file rather than executes it. HOWEVER, if I just type “localhost/contact.html” in my Chrome browser everythng works fine. And the database is updated fine. Any ideas?
    Thanks again for posting these files and the info you share.

    1. raghwendra ojha Avatar

      When the wamp server work, you need to open file using “localhost/contact.html” only in your browser. If you open your file in browser via right click with system path C:\\wamp… then it will be not work. The WAMP is providing web server(localhost) that need to run the web pages.

  4. Bhupathyraj Avatar

    Sir, Kindly help to resolve the following error:
    Warning: Undefined array key “txtName” in C:\xampp\htdocs\new\contact.php on line 43
    Warning: Undefined array key “txtEmail” in C:\xampp\htdocs\new\contact.php on line 44
    Warning: Undefined array key “txtPhone” in C:\xampp\htdocs\new\contact.php on line 45
    Warning: Undefined array key “txtMessage” in C:\xampp\htdocs\new\contact.php on line 46
    Contact Records Inserted

    1. raghwendra Avatar

      If you use the exact code it will not give any error. It is tested at my end. Did you download the code from Git Please let me know?

  5. ghost9099 Avatar

    why is the name and email showing “0”, even though I added values in those fields in the form?

    1. raghwendra Avatar

      Please check your database field name and email is Varchar? It may be the integer therefore it is showing 0

  6. talha Avatar

    i have successfully create database and also it store data on localhost successfully but now how can i connect that database on my html anchor tag

    please help

    1. hemant Avatar

      I didn’t understand your query. Why you would like to link the HTML anchor tag with the database?

  7. Devaki S Avatar
    Devaki S

    http://localhost/phpmyadmin/ this link isn’t working in my pc …what should i do … the link is showing msg as”HTTP Error 404.0 – Not Found The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.”

    1. raghwendra Avatar

      Did you start your XAMPP, WAMP, MAMP program? Did you start apache and mysql server? Please have seen the start movement of xampp above in picture.

  8. Marcelo Avatar

    I would like to thank you.
    after long time i achieved with your help.

    1. raghwendra Avatar

      You are welcome.

  9. Ron Avatar

    Aside from this login or contact features, do you have html codes for frontend for creating sales and inventory database. How do we start it?

    1. raghwendra Avatar

      Thanks @Ron, but I have not such a code. Please join the FB group so some would be help you.

  10. Mel Parrish Avatar
    Mel Parrish

    How can I improve the code, so that when data is entered, you are then taken back to the form, to keep adding more date?

    1. raghwendra Avatar

      Please add following code in contact.php in the last after closing of PHP tag. Let us know if you have more query
      <a href="contact.html" rel="nofollow ugc">Add New Record</a>

  11. Samba Avatar

    Thanks for this tut sir. really helpful 🙂

  12. ORUKU DANIEL Avatar

    i use WAMP, do i still need LAMP

    1. raghwendra Avatar

      If you have WAMP then no need to install another LAMP stack.

  13. Someone Avatar

    what is wrong here ?? it dont add in phpmyadmin

    1. raghwendra Avatar

      Please share your code.

  14. imran Avatar

    Hi, sir this code works properly and thank you so much. i am facing an issue actually i want to another html page to be opened after login but php page is opening.
    plz provide a solution how can i connect login page with homepage and also i want to store data of every page like data of delivery address page, login page etc

    1. raghwendra Avatar

      Yeah too much complex query, Hope you got the solution. If still you are looking for solution please join and post on facebook group

  15. r. Avatar

    hello, I am getting the following error

    Warning: mysqli_connect(): (HY000/1049): Unknown database ‘db_contact’ in C:\xampp\htdocs\contact\contact.php on line 5

    Fatal error: Uncaught TypeError: mysqli_query(): Argument #1 ($mysql) must be of type mysqli, bool given in C:\xampp\htdocs\contact\contact.php:17 Stack trace: #0 C:\xampp\htdocs\contact\contact.php(17): mysqli_query(false, ‘INSERT INTO `tb…’) #1 {main} thrown in C:\xampp\htdocs\contact\contact.php on line 17

    what went wrong?

    1. raghwendra Avatar

      Did you created your database with the table in phpmyadmin?
      Check your database port and put as a fifth parameter in the connection line.
      $con = mysqli_connect(“localhost”, “root”, “”, “db_contact”,”3308″);

  16. HELLO Avatar

    Will the above code work for HTML tables. If not then pls provide a code that can save the contenteditable changes to the database

  17. hesham aboulatta Avatar
    hesham aboulatta

    Hi . is there any explanation to how to get the data back from the database table and display it in the form.
    for example typing the name then display the rest of data in a form not in a table

  18. C.ARUN PANDIAN Avatar

    Parse error: syntax error, unexpected variable “$rs” in C:\xampp\htdocs\phpdoc\post.php on line 9

    1. raghwendra Avatar

      it may be your file didn’t download correction or you modified the file. this is working fine with other people.

  19. Tejansh Srivastava Avatar
    Tejansh Srivastava

    You have made a small mistake on contact.php page line no 5
    it should be : $con = mysqli_connect(‘localhost’, ‘root’, ”,’db_connect’);
    instead of : $con = mysqli_connect(‘localhost’, ‘root’, ”,’db_contact’);

    1. rangnath Avatar

      Thank you for notice the image and text. But in text we are using everywhere db_contact.

  20. Tejansh Srivastava Avatar
    Tejansh Srivastava

    How can I use salting (or any type of encryption) so that everybody’s password in the database can be seen in form of encryption and not in plain text.
    Thank you

    1. rangnath Avatar

      MD5 is a php function and mysql function. So this can convert password in a string and no on can see in mysql table what is the password. If you would like to keep it more secure you can contact a constant with the password before entering in database. And follow the same mechanism on login user.

  21. Unknown Avatar

    hello i have made form with html css javascript but not working

    Enter Your Name

    Enter Your Email

    Enter Your Mobile Number




    Your message has been sent. Thank you!

    Send Message

    and shows unidentified array key and even sometimes it shows blank what should i do please help me out

  22. luis santiago Avatar
    luis santiago

    man, i fixed that error in this way:
    1. in the first line u need to see the name of the database i put db_connect.
    2. in the 14 line u need to check the name of the table where it say tbl_contact, in my case i put db_contact in php my admin and because of that i was crying in front of my computer until i watched line 14 and realized it, now, i am a happier human

    1. raghwendra Avatar

      Great & Enjoy! Join this FB group for the latest update on Web development and coding –

  23. Engy Avatar

    Thanks so much for the code but it doesn’t update my database and doesn’t give any error.
    Can you please help me with this, thanks

    1. raghwendra Avatar

      yes please, how may I assist you? would you like to come online? please join this FB group and message their

  24. Dirk Robbertse Avatar
    Dirk Robbertse

    Hi when i debug the file in HTML it populates my contact.php file on the window

  25. Dirk Robbertse Avatar
    Dirk Robbertse

    That happens after i inserted user input

    1. raghwendra Avatar

      Yes, If an HTML form is submitted then it goes on contact.php as this is the form action. What do you want exactly?

  26. arawan Avatar

    when i press submit, it just goes on another page then display the php file in the browser. what”s wrong with the codes? i literally just followed your instructions, including the db,table names. yet it still just display the php file

    1. raghwendra Avatar

      If PHP code is displayed in the browser so It seems you didn’t install the PHP or any PHP environment like XAMPP or WAMP.

      1. Dirk Robbertse Avatar
        Dirk Robbertse

        Hi it was my fault i had WAMP and XAMP installed and both where tying tun run, it got executed thank you very much : )

  27. linus Avatar

    Where do i save my html and php files

    1. raghwendra Avatar

      IF you installed your Xampp you have to go to this Xampp directory htdocs folder. In this article, our Xampp is in E: drive so the folder location is E:\xampp\htdocs

    2. bharath Avatar

      in our -win-7c-xampp- htdocs -and our file

  28. Christin Avatar

    I have tried to connect my PHP code to the database in the PHPMyAdmin, and has successfully connected, but when I try to execute the query, it is not doing anything. No error in the code, but no change in the database too.

    $sql1=”INSERT INTO user (‘U_id’,’F_name’,’L_name’,’Email’,’Password’,’Role’,’Emergency’,’Emergency_id’) VALUES (‘$U_id’,’$F_name’,’$L_name’,’$Email’,’$Password’,’$Role’,’$Emergency’,’$Emergency_id’)”;
    echo ” The data have been entered. “;

    If possible could you look into this?……..

    1. raghwendra Avatar

      Can you please share the complete code with the database on our FB group

  29. sheshan Avatar

    we need to install XAMP to the website folder location or anywhere ?

    1. sheshan Avatar

      because when i press the contact button in website, it show me the php code

  30. sheshan Avatar

    i installed XAMP but when i press contact button on website it shows me the php code ? can you help me ?

    1. raghwendra Avatar

      Did you keep your code in \xampp\htdocs?

  31. Jomarie Avatar

    Hello, can you help me. I did your instruction and tweak it a little. Can you please tell me what’s wrong on my code. It keeps erroring.
    here’s the error message: Fatal error: Uncaught Error: Class “mysqli_connect” not found in C:\xampp\htdocs\PR\database\adminlogin.php:3 Stack trace: #0 {main} thrown in C:\xampp\htdocs\PR\database\adminlogin.php on line 3

    Here’s my code:

    Admin Log In

    Admin Log In





    Thank you! I’m new to this, so I hope you can help me please.

  32. Jomarie Avatar

    Nevermind I found the problem. But still thanks! You helped me a lot

  33. Jomarie Avatar

    Hello here I am again hehe. First, all answer on the html form goes to my database, but it keeps showing me only numbers? Why? Theres no letter in my database only numbers? Can you help me Thanks.

    1. raghwendra Avatar

      It may be your database fields type is integer rather than varchar.

  34. Jomarie Avatar

    Hello there again, I fixd it. Can you do a tutorial on how to error repeating accounts? Cause I tried logging in same accounts and it keeps adding on my database. Please that would help me a lot. Thanks

    1. raghwendra Avatar

      Didn’t get you more please elaborate on your question.

  35. Mihut Denisa Avatar
    Mihut Denisa

    Can someone help me?
    After submiting why do I get only this: “Are you a genuine visitor?” every time I acces the website?

    1. raghwendra Avatar

      What are you submitting? Please share in details.

  36. Abhishek Saxena Avatar
    Abhishek Saxena

    Hi tried using the code the html part runs fine but as soon as i press submit this error pops up

    Object not found!
    The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.

    If you think this is a server error, please contact the webmaster.

    1. raghwendra Avatar

      Are you using any online server or xampp software on your machine? Did you install the xampp?

  37. Engy Saeed Avatar
    Engy Saeed

    everything is working, but I want to the data to be emailed by me but it always not working, I tried many solutions and all solution on google no luck. Wish you can help

    1. admin Avatar

      Please share your email code ?

  38. Mihut Denisa Avatar
    Mihut Denisa

    Hello! It was my mistake, I didn’t put the right names when getting the post variables.
    Thank you for replying!

  39. Amir Avatar

    Hello there!
    Duuuuuuude thank you so much. You are such a great teacher, I really enjoyed the whole tutorial. This was exactly what I was looking for.

    1. raghwendra Avatar

      your are welcome.

  40. anonymous Avatar

    Hi sir, i was having an issue with this error “Not Found The requested URL was not found on this server.” i copied your code and followed step by step but still im recieving this

    1. raghwendra Avatar

      Do you keep your files in folder xampp/htdocs?

  41. Hatler Avatar

    The data doesn’t get inserted into the database. After clicking submit it shows a blank page

    1. raghwendra Avatar

      It seems you didn’t read the article carefully. You may download code from the git hub directly

  42. vhutshilo Avatar

    hi ,my cuoding is not running

    1. raghwendra Avatar

      How we help you? Please join FB group.

      1. brix john solivio Avatar

        can i join your group sir. I’m willing to learn progamming language

  43. ozcan Avatar

    i have;
    Fatal error: Uncaught mysqli_sql_exception: Unknown database ‘db_formulaire1’ in C:\xampp\htdocs\www\jeu\inscription.php:5 Stack trace: #0 C:\xampp\htdocs\www\jeu\inscription.php(5): mysqli_connect(‘localhost’, ‘root’, ”, ‘db_formulaire1’) #1 {main} thrown in C:\xampp\htdocs\www\jeu\inscription.php on line 5

    Please help me (i speak french)

    1. raghwendra Avatar

      Did you create your database by the name ‘db_formulaire1’ in MySQL? Please share

  44. georgia Avatar

    When i press submit on my form it just displays to me my php code in the browser, any ideas how to fix this?
    i am using wamp with phpmyadmin btw

    1. raghwendra Avatar

      As you told phpmyadmin with wamp is working well. it may be you didn’t start the php tag in starting. Or php not active or you open php code without localhost/yourfilename

  45. Kilian Avatar

    Also got the problem as some others that php was displayed as plain text in Browser.
    The solution is to not open C:/xampp/htdocs/contact/contact.html but to open http://localhost/contact/contact.html.

    1. raghwendra Avatar

      Please install the xampp or wamp any server in your computer so that you will be able to see the pages.

  46. Prx Avatar

    hi i am using Xampp.I Have Created Database with same name i cloned your code but when submitting it shows “This page isn’t workinglocalhost is currently unable to handle this request.
    HTTP ERROR 500”.

    1. raghwendra Avatar

      The location of keeping files or folder is \xampp\htdocs . Did you keep your folders here.

  47. malaika Avatar

    Hi sir i am facing an issue

    1. raghwendra Avatar

      what is the error? please let me know

  48. Shekhar Nathan Avatar
    Shekhar Nathan

    $con = mysqli_connect(‘localhost’, ‘root’, ”,’db_contact’);
    The “db_contact” is our database name that we created before.
    Mr. Raghavendra.

    Is this correct or it should be db_connect as that is the database we have in server.
    Pls can you help with this as i am getting an error.

    1. raghwendra Avatar

      if the name of database “db_connect ” so you have to put it on place of “db_contact”.

  49. Gichtie Avatar

    Hi, I had the same problem. You have to make sure, that you realy call the “contact.html” by using path “localhost/contact.html” in your browser. If you just open the file from the os-explorer the php.ini is not used and the os just thinks it has to open the php file, not executes it. Just try “localhost/contact.html” as url in your browser and I’m pretty sure it will work.

    1. raghwendra Avatar

      Didn’t you brother?

  50. Samir Avatar

    I follow all the steps mentioned above, but when running I received the following message from the browser (File not found , It may have been moved, edited, or deleted.

    1. raghwendra Avatar

      it seems you are loading wrong path of files. If the path is incorrect you are getting this message.