Connecting to the Database
A database is a collection of data. 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.
When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
Developers prefer POST for sending form data.
Next, lets see how we can process PHP forms the secure way!
Collecting customer form data is a common task in web development. Contact forms make your site more professional and send a clear signal that you’re interested in doing business with your potential clients. The lack of one could make your business seem outdated or unprofessional. People are more likely to patronize your products if you’re highly accessible. This is a great way to increase your business’s visibility.
Other reasons to implement a contact form:
- It makes your site more professional
- Security
- Makes yourself more reachable
- Automate email responses
Today, we will be learning how to insert customer form data into a MySQL database using HTML and PHP. We will be creating an HTML form and a PHP script to insert the data into the database using
phpMyAdmin
.
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 – Complete Form Example
Here is the complete code for the PHP Form Validation Example:
Get Started With Machine Learning
Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.
This Answer outlines how to use PHP to connect an HTML form to a MySQL database. We’ll use XAMPP as the server software to create a database and run PHP.
We’ll use the below steps to create a connection:
The method to configure a PHP development environment with XAMPP is shown here.
This Answer explains what an HTML form is and how to create it.
In this step, we’ll create a simple MySQL database since our server is already running.
We’ll open the browser and type http://localhost/phpmyadmin/. This redirects us to the PHP admin page, where we can create and manage databases. Click on the New option in the menu panel on the left side. The image below demonstrates this:
On the next page, we’ll choose a name for our database and click on Create, as shown:
Next, we’ll create a table in the database. We’ll add a table name and choose the number of columns:
Once we click on Create, we’ll be redirected to the following page:
Here, we’ve to give details regarding the table. The columns correspond to our fields in the HTML form. We may also assign each column a data type, characters length, or special privileges such as the
Once we’re done, we’ll click on Save. Our first table in the database is created.
Now that we have our database and server ready, we’ll create the necessary files. We’ll begin by opening the folder directory containing XAMPP. We traditionally find this folder in Local Disk E or Local Disk C. For Linux users, this will be in the
Computer/opt/lampp
directory.
Within that folder, open another folder titled
htdocs
and create a folder in it. We can name it anything, but for this tutorial, we’ll name it
educativeform
. This new folder will contain our HTML and PHP files.
htdocs/educativeform|-> form.php|-> index.html
The following code snippet contains the HTML code for the form:
Note: If we click on the submit button, it will given an error since we haven’t yet connected it to the database.
POSTis the connection type to send the HTML form entries. The
actionattribute has the value
form.php. This is the name of the PHP file in the working directory, and the form entries will be sent to this file upon submission.
formfields. The last
inputtype is a
buttonthat submits the field values to the PHP file.
To confirm that our form is ready, we’ll type
localhost/educativeform
in the browser. 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:
$_POSTas connection type to get HTML form entries.
nameattribute in the
inputlabels of the HTML code.
Finally, we’ll connect our HTML form to the database using PHP. The code below is an addition to the previous code snippet, as shown:
mysqli_connectto create a connection.
If everything is running without errors, we should be able to add our HTML form details in the MySQL database.
RELATED TAGS
CONTRIBUTOR
Careers
GETPOST
Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 => value3, …)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope – and you can access them from any function, class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
Processing form data:
We can collect the form data submitted through our HTML form that we’re going to create. We can use the
$_REQUEST
variable to collect the data.
close(); ?>
Process:
First, you’ll want to make sure that you already have XAMPP Server installed on your local machine. Once it’s installed, let’s begin by first opening up our Xampp application. In my case, I am using a Macbook Pro so things may look a little different if you’re using Windows or another operating system. You’ll want to make sure you have the following services running when you open up your Xampp application:
- MySQL Database
- Apache Web Server
Now we can navigate over to
localhost/phpmyadmin
and create a database and table.
-
Click on
New
and then type in the name of your Database. We are going to name our database
SampleDB
. Once complete, go ahead and click the
Create
button.
Next we can create the table we want to use named
SampleTable
. Make sure to set the number of columns to 5. Once complete, click the
Create
button.
Now that our Database and Sample table is created, we can enter our columns and click on save.
Make sure you enter the correct data type for each column.
-
first_name
-
last_name
-
gender
-
address
Also, make sure to add the appropriate type of
VARCHAR
to each item as well.
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.
Contact Form - PHP/MySQL Demo Code
Now your form is ready. You may test it in your localhost link http://localhost/contact/contact.htmlIn the next step, I will go with creating PHP / MySQL code.
Create the html form
Now it’s time to create our HTML form. We will be using this form to send the data to our database.
Filename:
index.php
Sample Form
Storing Form data in Database
HTDOCS Folder
We can access this folder by opening up our Xampp application and then clicking on
Open Application Folder
.
This will open up our Xampp files directory. Navigate to the
htdocs
folder and copy your
index.php
and
insert.php
files directly into this directory. This will overwrite the existing file. Now we can head over to
localhost/index.php
to fill out the form submit it to our database.
Fill out the form and then click
submit
. Great! it looks like our data has been successfully stored in our DB.
Head over to
localhost/phpmyadmin
and select your database to ensure that our data was successfully inserted.
PHP – A Simple HTML Form
The example below displays a simple HTML form with two input fields and a submit button:
Example
Name:
E-mail:
When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named “welcome.php”. The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The “welcome.php” looks like this:
Welcome
Your email address is:
The output could be something like this:
Your email address is [email protected]
The same result could also be achieved using the HTTP GET method:
Example
Name:
E-mail:
and “welcome_get.php” looks like this:
Welcome
Your email address is:
The code above is quite simple. However, the most important thing is missing. You need to validate form data to protect your script from malicious code.
Think SECURITY when processing PHP forms!
This page does not contain any form validation, it just shows how you can send and retrieve form data.
However, the next pages will show how to process PHP forms with security in mind! Proper validation of form data is important to protect your form from hackers and spammers!
Conclusion
You have just completed the basic steps to store data in a database using HTML and PHP. You can now use this method to create any kind of form you like and attach it to a phpMyAdmin database.
🤝 Thank you so much for taking time out of your day to read this Article! I hope it helped you out and you learned something new today! Please leave a comment if you have anything you’d like to add. I’d love to hear from you!
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;
PHP
data stored in a database successfully."
|