Creating Simple Form using PHP and MySql

HTML form is an essential part of Web development process, it allows us to gather data from user inputs and we can do various things with the data we receive from user, we can send email, change interface, layout or save the data directly to our MySql table. Today we are going to create a simple HTML form that will collect data from user, such as user name, email and message text, and using PHP we will save the collected data into our MySql database table. This is a common scenario in Web development world where we often need to store various data from users.

Step 1 : Create HTML Form

To create an HTML form just open your HTML editor and put the following code within the <body></body> tag of your HTML page. This will be a plain HTML page, no dynamic server side coding such as PHP is required here. We will talk about PHP in next step.
HTML
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
<form method="post" action="process.php"> Name : <input type="text" name="user_name" placeholder="Enter Your Name" /><br /> Email : <input type="email" name="user_email" placeholder="Enter Your Email" /><br /> Message : <textarea name="user_text"></textarea><br /> <input type="submit" value="Submit" /> </form>
As you can see in HTML above, I have <form></form> tag, which contains several input field tags like user name and e-mail, and you can always add more input fields if you want to collect more data from user. These input fields can have different attributes, such as name of input field, its type, maxlength, placeholder etc. Even though we only need name and type attributes, we can always play with different attributes as per our project needs.

Step 2: PHP process page

Our HTML form is ready to take inputs from users in above example, we now need to create a PHP page to collect data from this form. PHP is a server-side language, it performs all tasks on the server and end users do not see anything unless there's errors or outputs. Notice action attribute in HTML form tag above? It points to process.php and it means all the values of input fields will be sent to process.php. All we need to do now is create process.php. To simply output captured values through HTML form, we can write something like this :
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
<?php //process.php if ($_SERVER["REQUEST_METHOD"] == "POST") {//Check it is coming from a form $u_name = $_POST["user_name"]; //set PHP variables like this so we can use them anywhere in code below $u_email = $_POST["user_email"]; $u_text = $_POST["user_text"]; //print output text print "Hello " . $u_name . "!, we have received your message and email ". $u_email; print "We will contact you very soon!"; } ?>

Step 2: PHP Validation

If you have tested above code, you will realize that it is really easy to capture and display values from input fields. But our code is still vulnerable to various unknown attacks. For example, if I put <a href="http://google.com">Sanwebe</a> in name field, it will output a link to Google page. Storing such untrusted data can lead to various code injection exploitations, our website could be easy target of attackers. So we need to clean such inputs before we actually process the data.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
<?php //process.php if ($_SERVER["REQUEST_METHOD"] == "POST") {//Check it is comming from a form $u_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING); //set PHP variables like this so we can use them anywhere in code below $u_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL); $u_text = filter_var($_POST["user_text"], FILTER_SANITIZE_STRING); if (empty($u_name)){ die("Please enter your name"); } if (empty($u_email) || !filter_var($u_email, FILTER_VALIDATE_EMAIL)){ die("Please enter valid email address"); } if (empty($u_text)){ die("Please enter text"); } //print output text print "Hello " . $u_name . "!, we have received your message and email ". $u_email; print "We will contact you very soon!"; } ?>
I have used PHP filter_vars to clean-out user inputs, and also checked whether posted values are empty. These small measures will insure protection from numerous code injections and make our script attack-proof, so never forget to check invalid data whenever you can.

Step 3: Storing data in MySql

Using PhpMyAdmin interface, you can easily create a new table to store user information. But if you are lazy, you can just drop following MySql code in SQL query box, it will create a new table called "users_data" for you in MySql.
MYSQL
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
CREATE TABLE IF NOT EXISTS `users_data` ( `id` int(11) NOT NULL, `user_name` varchar(60) NOT NULL, `user_email` varchar(60) NOT NULL, `user_message` text NOT NULL )AUTO_INCREMENT=1 ; ALTER TABLE `users_data` ADD PRIMARY KEY (`id`); ALTER TABLE `users_data` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
Once we have the database table, we can continue working on process.php. As you can see in example below, I have added few more PHP code, on top of the code I have provided MySql login info which will be used to connect to MySql database. Once the connection is open, using MySql INSERT query we will store user inputs into database table.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") {//Check it is comming from a form //mysql credentials $mysql_host = "localhost"; $mysql_username = "root"; $mysql_password = ""; $mysql_database = "test"; $u_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING); //set PHP variables like this so we can use them anywhere in code below $u_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL); $u_text = filter_var($_POST["user_text"], FILTER_SANITIZE_STRING); if (empty($u_name)){ die("Please enter your name"); } if (empty($u_email) || !filter_var($u_email, FILTER_VALIDATE_EMAIL)){ die("Please enter valid email address"); } if (empty($u_text)){ die("Please enter text"); } //Open a new connection to the MySQL server //see https://www.sanwebe.com/2013/03/basic-php-mysqli-usage for more info $mysqli = new mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database); //Output any connection error if ($mysqli->connect_error) { die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error); } $statement = $mysqli->prepare("INSERT INTO users_data (user_name, user_email, user_message) VALUES(?, ?, ?)"); //prepare sql insert query //bind parameters for markers, where (s = string, i = integer, d = double, b = blob) $statement->bind_param('sss', $u_name, $u_email, $u_text); //bind values and execute insert query if($statement->execute()){ print "Hello " . $u_name . "!, your message has been saved!"; }else{ print $mysqli->error; //show mysql error if any } } ?>
That's it, process.php is now ready to collect data from HTML form. You can do various things once the data is stored in the table, you can always read MySqli Basic usage article if you are wondering how to retrieve and display saved data. I hope you enjoyed reading this article and it helped you with your projects.
New question is currently disabled!