Program to create a login form in PHP

Hey Guys,
In this PHP tutorial, you are going to learn about creating a simple login form in PHP.

This login form is gonna accept the data verify it with our database values and if the user exists then gonna print successful else it would print failed.

Creating a login form using PHP:

To create a login form we have to use both HTML and PHP.

The steps to create a login form is as follows.

Algorithm:

  1. First of all, create a connection to our database.
  2. Now create an HTML login form having 2 inputs username and password.
  3.  First, create a for loop to know whether the submit button is pressed or not do that using isset() keyword.
  4. Import the values from the HTML code.
  5. Create MySQL query commands to select data from the database.
  6. Now use a function known as mysqli_num_rows().
  7. This function returns 1 if both are found in one row in database else returns 0.
  8. Now create a for loop to check the value is 1 or not and print the given text.
  9. Now the PHP code is ready to execute.

Example:

Consider we have a database named project which has a table login with 2 parameters as input username and password.

TABLE:

username            password

ram                  123456

jonny                fagajnjgd

Let assume the above-mentioned table is our login table in our database.

<?php
$servername="localhost";
$username="root"; 
$password="";
$dbname="project";
$q=mysqli_connect($servername,$username,$password,$dbname);
?>
  

<html>
<head>
<title>loginpage</title>
</head>
<body>
<h1> login form</h1><br><br><br><br>
<form action="" method="post">
<table>
<tr><td>ENTER YOUR USERNAME</td><td><input type="text" placeholder="username" name="usernameentered" required></td></tr>
<tr><td>ENTER YOUR PASSWORD</td><td><input type="password" placeholder="password" name="passwordentered" required></td></tr>
<tr><td><input type="submit" name="submit" value="submit"></td></tr>
</table>
</form>
</body>
</html>

<?php  

if(isset($_POST['submit']))

 { 

$a=$_POST["usernameentered"]; 

$b=$_POST["passwordentered"]; 

$query1="SELECT * FROM LOGIN WHERE username='$a' && password='$b'";

$data1= mysqli_query($q,$query1); 


$t= mysqli_num_rows($data1);

 if($t==1) 

{

 $_SESSION['user']=$a; echo "successful; 

}

 else

 echo "failed";

}

?>

Here if we enter both the user name and password correctly then we would get output like this

successfull

In any other case, we would get output like.

failed

Also, read:

 

Leave a Reply

Your email address will not be published. Required fields are marked *