How to validate login form and database connectivity

How to validate login form and database connectivity

Hi everyone! From our last post we have started to discussed about how to create a login form using PHP MySQL. Not only using PHP we discussed how to create login form using bootstrap as well as. Up until now we learned how to create  the login form and HTML, bootstrap components in the login form. If you couldn’t read the post you better learn how to. In order to continue with the validation and database querying firstly you need to know how to create a login form. Therefore please read this article. How to create a login form using PHP MySQL. Today we are going to learn how to validate login form and database connectivity.

Now we will move to today’s topic. Today we are going to learn how to validate a login form using jQuery. And also how to create login form with MySQL. We will learn validations in a login form and how to pass data to the backend using Ajax. In other words how to send data to the server using ajax concept. And also today we will learn validate login  details with a database and how to create successful login screen. The full cycle of login form we are going to completely today.  By the end of this post you will be able to create a login form successfully. Let’s get started.

What is data validation/ Why we use data validation?

In a system we request user to enter some data. Those data we call as inputs. Users have to fill and submit them. When filling the forms users are doing mistakes. They might have enter incomplete, wrong, incompatible data. That can leads the system to unreliable state. Then the data appear in the system is not correct. Therefore before sending the data to the database and saving it we have to validate them. There are two types of data validations we use to validate data in the systems.

  • Client side validation – Here we do the validation in the client machine. Before send to the server. We can use jQuery, regular expressions for that. This validation is fast.
  • Server side validation – In this validation we perform after sending data to the web server. In the server we do the validation. We can do this validation by using PHP or any language you use to develop the system.

When you are developing a system it is better if you can use both types of validations. As an example for the data validation assume a form is asking to enter contact number from a user. Usually contact number is 10 digits length field. Anyway when typing users can type only 9 digits and mistakenly submit the form. If we didn’t use a validation system will accept 9 digit input and save it in the database. Later when someone trying to make a call they find the data available in the system is not correct. To prevent this kind of errors we use validation.

How to add jQuery to my project?

Before writing validations or using Ajax, we have to add jQuery to our project. We can do it by firstly downloading the jQuery. Secondly adding .js file to our project.  You can download the jQuery from jQuery official site. When adding please carefully give the path. If your path is wrong jQuery won’t work. You have to add the min.js or js file path to the header. See how it was done in the image.

How to add jquery to the PHP project
How to add jQuery to the PHP project
Tip
If you are using bootstrap in your project. Firstly you need to add jQuery path. Then add poper.js. After that add bootstrap.js file. If not your project JavaScript not work properly.

 

jQuery validations for a login form

The validation in a login form is simple. That is we have to send data to the server if both user name and password has typed by the user. So we have to check at the button click whether the two fields are empty or not. If empty we have tell refill the form. If not we can send data to the backend. We write the jQuery code inside the script tag.

<script type="text/javascript">

//Type your jQuery code here

</script>

We can’t just write jQuery inside script tag. Inside the script tag we write jQuery starting code to write the jQuery code. We write all jQuery codes inside that. That code is.

$(document).ready(function(){});

Inside the jQuery code we can start writing the validation. You already know we have to start the data validation after the button click and we have two conditions. They are form empty or not empty. We need to apply a simple logic that is IF clause. We will look at the code. Here is the code.

$("#btnlogin").click(function(){
var uname,pass;
uname = $("#txtuname").val();
pass = $("#txtpass").val();
if(uname=="" || pass==""){

swal("login Error", "Fill all field", "error");
}
else{

//AJAX code need to write here

}

Here inside the else statement we need to write the AJAX code to pass the dat to the backend. Firstly we created two variables to store the user name and password values. From the function val() we can get the value of the entered field. Since we are using id you have to use# sign. If you call the element using class use . sign. txtuname and txtpass are the id of the username and password input tag. Now let’s move the AJAX code.

How we can send form data to the server using Ajax

var fdata = $("form").serialize();
var url = "loginhandle.php" // File we send data
$.ajax({
method:"POST",
url:url,
data:fdata,
dataType:"text",
success:function(result){
},
error:function(eobj,etxt,err){
console.log(etxt);
}
});

This code has to come inside previous code else clause. For method we can use either POST or GET. Here we use the concept called serializability. It will give us the ability to send all form data at once as name value pairs.

Tip
When you use serialize method remember to add names in the HTML tags. The HTML Tag input has both id and name attribute. Give same value to both id and name attributes. If you didn’t add name attribute then this method won’t work.

By now we have done all the works. Up until this our form validates data and send them to the backend. Now all we need is validate user data with the database data. For that we have to have the database connection and write SQL queries. Then we will see how to do that.

How to connect database to the PHP project

To connect database to the PHP projects we have several methods. We can add database connection string to the code and get the connectivity. Yet today I am not going to use that. Today I will tell you easy method for the development. If we use connection string we have to require that file every where. In this method we will create a database object. Whenever we need to database connectivity we can create database object and execute query. This method pretty much easier in the development stuff.  Since we are going to return a database object we will use OOP here. We will create a class for that. Let’s see the code.

<?php
class Connection{
public static function conn(){$host ="localhost";
$uname = "root";
$password = "";
$dbname = "dbname"; //give your database name here$dbobj = new mysqli($host,$uname,$password,$dbname);if($dbobj->connect_errno){
echo("db connection error <br>");
echo("Error text: ".$dbobj->connect_error);
exit;}
return $dbobj;}
}?>

After creating the database connection most of our work is over. Now we have the db connection. Our data pass to the backend. What is the left is to validate send data with the database. So let’s see how to do that.

How validate login data with database MySQL

You have to write this code inside the PHP file you sent form data. Firstly we have to add the PHP file which has the database connection.  Top of the PHP page require the database PHP file. Then write the code. Since this is a login attempt we have to create a session. We can create it at the top of the page.

After SQL query executed if entered data is correct it will return one database record. Because in a database user name is the primary key usually. Two user names cannot be same. If data is matching correctly then it will return 1 record or zero record. Again we find a IF logic. All we have to do is write the code to implement this logic. If you want to learn about full database configuration in a PHP project. Please read this post. How to create a PHP project.

<?php
//To start the session
session_start(); 
//to require dbconnection.
require_once("dbconnection.php");
//catch the values send from the form
$uname = $_POST["txtuname"]; 
$pass = $_POST["txtpass"];

//database object
$dbobj=Connection::connect();
$sql="SELECT * FROM tbl_users WHERE usr_name='$uname';";
$result=$dbobj->query($sql); //queryif($dbobj->errno){
echo("SQL Error:".$dbobj->error);
exit;
}//number of rows
$nor=$result->num_rows;if($nor>0){
$row = $result->fetch_assoc();
// If password hashed used in db convert it to hash value
$pass= md5($pass); 
echo("1"); //This value show to the front end 
}
else{
//if nor less than 0
echo("0");}
$dbobj->close();
?>

Now all set. Our full cycle completed. We  have to done small change to further process.  Now Our data pass to the back end and validate with database and giving us a result. That result is either 0 or one. It will show to the front end. Based on that we can process login function work. If the echo value is zero we have to show an alert to re-enter data. If not we can direct them to a home page. So you have to add this small code inside AJAX success to do those processes.

if(result=="0")
alert("User name or password incorrect");
else 
location.href="home.php";

 

I will give a small tip here. When we show error messages in system for login we don’t say directly user name is wrong or password is wrong. What we say is password or user name incorrect. This we do for the security purpose. o don’t show what is incorrect directly in your error messages.

Conclusion

Today from this post we have discuss the complete process of creating a login form. Now you can create a login form by your own. I hope you learned so much from this. You want  to learn more about jQuery you can visit jQuery website for jQuery documentation. You can visit this post if you like. There you can find all the details required to do a PHP project. How to create a PHP project. If you like this post please share it among your friends. If you have any suggestions you can comment it and let us know. We will meet with another interesting topic. Till then goodbye!

 

Audy Ranathunga

Audy Ranathunga, Author of myexamnote is our most experienced author. She has been working as a blog post writer for 4 years. She joined with myexamnote before 1 year ago and she has contribute lots of valuable posts for readers.

Leave a Reply