DEV Community

Adnan Alam
Adnan Alam

Posted on • Edited on

Create a Web Server and save form data into MySQL database using PHP (Beginners Guide)

Static pages are great for showcasing your projects. However, if you would like to get data from clients and save it into the server or allow clients to retrieve data from your server then you would need a dynamic webpage. In this tutorial I will show you how to setup a web server, collect data and save into the server database.

Key concepts

Before we begin let's review a few HTTP methods. GET requests data (text/file) from the server. POST requests server to accept data (text/file) into the server. PUT requests to modify a specified resource in the server. DELETE requests server to remove a specified resource. We will only be using POST, and PUT in this tutorial.

Environment Setup

We will have to setup the server before we can begin to code for the website. There are many other languages and databases that can be used for this purpose, however this tutorial will only cover PHP, MySQL database and Apache web server. We will go over two methods, Linux, and Windows. I recommend using Linux as it is much simpler to get started. If you already have environment setup then move on to the coding block. If you do not have a Linux environment setup, then I would recommend using virtual-box to setup a basic Linux VM and run Ubuntu on it.

Windows

First in Windows, go ahead and install WAMP server from here. This will take a while as you will have to install a lot of packages. Please ensure all of the Visual C++ packages from the readme.txt file have been installed before moving forward as this can cause a lot of headache later on. Once installed then please open your browser then go to 'localhost' without the quotation marks. If you see a webpage then you are good to go. We will be working in the www/html folder inside of the wamp directory (the installation path). On the right hand corner you will see a green W icon indicating that the server is online and working.

I would recommend checking out this video if you still are not sure how to setup the wamp server.

Linux (Ubuntu)

If you have a different distribution then please use the appropriate package manager to install the tools necessary. Start off by installing Apache2.
sudo apt-get install apache2
Then ensure the service is running.
sudo service apache2 start

Afterwards install mysql and go through the setup. Please remember your root password.
sudo apt-get install mysql-server
sudo /usr/bin/mysql_secure_installation

Then install php and we should be ready to go.
sudo apt-get install php
sudo apt-get install php-mysql
sudo /etc/init.d/apache2 restart

Please ensure you install the php-mysql package as without it you will most likely get driver error.

Our working directory will be /var/www/html.

Apache2

In order to create new projects you will be creating new .conf files per project which will store the virtual host configurations. Please look at the existing config file to get a better understanding of this. For Linux this file can be found in the /etc/apache2/sites-available/ directory. Please check the file named 000-default.conf if available, otherwise just read any .conf file in that directory to get an understanding of the format.

Code

Once everything is setup please create a new file inside of the html folder (or your working directory if you have changed the Apache configurations).
We will start by creating a new file in the html directory.
sudo touch /var/www/html/form.html
Then go ahead and edit the file and populate it with some basic html code.
sudo nano /var/www/html/form.html



<head>
<title>
Test Page
</title>
</head>
<body>
<form action="form_submit.php" class="alt" method="POST">
<div class="row uniform">
<div class="name">
<input name="name" id="" placeholder="Name" type="text">
</div>
<div class="email">
<input name="email" placeholder="Email" type="email">
</div>
<div class="message">
<textarea name="message" placeholder="Message" rows="4"></textarea>
</div>
</div>
<br/>
<input class="alt" value="Submit" name="submit" type="submit">
</form>
</body>



Enter fullscreen mode Exit fullscreen mode

Database

Now let's setup the database to so that we can store the information. I will only cover creating database and table in Linux. First login
mysql -u root -p



create database dev_to;
use dev_to;
create table test(
    id int NOT NULL AUTO_INCREMENT,
    name varchar(255),
    email varchar(255),
    message text,
    PRIMARY KEY (id)
); 


Enter fullscreen mode Exit fullscreen mode

Let's make sure this works.
describe test;
output should look like:

Let's exit out.
exit
Now we are finally ready for the PHP code that will actually handle the data and save it into the database.

Form Handling

Start by creating a new file named form_submit.php.
sudo touch /var/www/html/form_submit.php
Now let's populate it with some code.
sudo nano /var/www/html/form_submit.php
Now try the code below which should persist the data into the specified table in the database.



<?php
$host = "localhost";
$db_name = "dev_to";
$username = "root";
$password = "password";
$connection = null;
try{
$connection = new PDO("mysql:host=" . $host . ";dbname=" . $db_name, $username, $password);
$connection->exec("set names utf8");
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}

function saveData($name, $email, $message){
global $connection;
$query = "INSERT INTO test(name, email, message) VALUES( :name, :email, :message)";

$callToDb = $connection->prepare( $query );
$name=htmlspecialchars(strip_tags($name));
$email=htmlspecialchars(strip_tags($email));
$message=htmlspecialchars(strip_tags($message));
$callToDb->bindParam(":name",$name);
$callToDb->bindParam(":email",$email);
$callToDb->bindParam(":message",$message);

if($callToDb->execute()){
return '<h3 style="text-align:center;">We will get back to you very shortly!</h3>';
}
}

if( isset($_POST['submit'])){
$name = htmlentities($_POST['name']);
$email = htmlentities($_POST['email']);
$message = htmlentities($_POST['message']);

//then you can use them in a PHP function. 
$result = saveData($name, $email, $message);
echo $result;
}
else{
echo '<h3 style="text-align:center;">A very detailed error message ( ͡° ͜ʖ ͡°)</h3>';
}
?>


Enter fullscreen mode Exit fullscreen mode

Now your website should be able to handle forms and save it onto the local database.

Here's a sample output from my test run:


Note: Please let me know about any issues you are having with this. The tutorial was created to help people get started on their journey to dynamic web development. If anything is unclear, or any information is inaccurate please let me know so I can correct it A.S.A.P.

Top comments (4)

Collapse
 
snargleflop profile image
Snargleflop

I tried this and everything went well. The only problem I have is that my submit button is a text box with the word submit

Collapse
 
satellitebots profile image
Adnan Alam

Hey, sorry I wasn't able to address this sooner, I'm glad you tried this out. Please describe your problem in more detail if possible. I would also highly recommend checking out Laravel as that can streamline PHP development. Cheers!

Collapse
 
mir7867 profile image
mir7867 • Edited

i followed exactly the same but i get this error and also iam not abel to store any data in my database!

Collapse
 
loco11011 profile image
loco11011

amazing, thanks man.
simple and short, just what i was looking for