Raghwendra Web Services Blog helps You & Your Business Grow

rwsragh@gmail.com wdraghwendra
Logo

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 storing HTML form input field in MySQL database connection in a db table using the PHP programming with example . This article provide you HTML form, DB + Table SQL code, Bootstrap 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 (for Mac OS) 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 http://127.0.0.1 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.

Watch Video

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 http://127.0.0.1/phpmyadmin/ 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`
--

CREATE DATABASE IF NOT EXISTS `db_contact` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `db_contact`;

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

--
-- Table structure for table `tbl_contact`
--

DROP TABLE IF EXISTS `tbl_contact`;
CREATE TABLE IF NOT EXISTS `tbl_contact` (
`id` int(11) NOT NULL,
  `fldName` varchar(50) NOT NULL,
  `fldEmail` varchar(150) NOT NULL,
`fldPhone` varchar(15) NOT NULL,
`fldMessage` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_contact`
--
ALTER TABLE `tbl_contact`
ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_contact`
--
ALTER TABLE `tbl_contact`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

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="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact Form - PHP/MySQL Demo Code</title>
</head>

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

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.

<?php
// 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);

if($rs)
{
	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

 

 

By raghwendra

Me a freelance web developer from new delhi india. visit me

99 comments

  1. 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. I follow the steps , but failed to connect DB, i receved a messege(php not found , editd or deleted) )

  2. 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. 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.

  3. 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

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

  5. 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

  6. 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. 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.

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

  8. 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?

  9. 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. 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>

  10. 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. Yeah too much complex query, Hope you got the solution. If still you are looking for solution please join and post on facebook group facebook.com/groups/226548845512051/

  11. 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. 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″);

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

  13. 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

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

  15. 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. Thank you for notice the image and text. But in text we are using everywhere db_contact.

  16. 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. 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.

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

    Enter Your Name

    Enter Your Email

    Enter Your Mobile Number

    Subject

    Message

    Loading

    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

  18. 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

  19. Hi
    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

  20. 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. Hi it was my fault i had WAMP and XAMP installed and both where tying tun run, it got executed thank you very much : )

    1. 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

  21. 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’)”;
    $rs=mysqli_query($con,$sql1);
    if($rs)
    {
    echo ” The data have been entered. “;
    }
    mysqli_close($con);

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

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

  23. 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:
    html:

    Admin Log In

    Admin Log In

    Username

    Password

     

    database:

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

  24. 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.

  25. 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

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

  27. 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.

  28. Hi
    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
    Thanks

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

  30. 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.

  31. 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

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

  33. 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)

  34. 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
    thanks

    1. 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

  35. 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”.

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

    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.

  37. 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.

  38. 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.
    ERR_FILE_NOT_FOUND).

Comments are closed.