Hey there,

For this post we’ll continue from my last post. On my last post, we created a login form without the use of database and sessions. This post is meant to teach you how to create a login form with database and sessions.

First of all,

Since we use a database, we need to create one. For this tutorial purpose, I created a database called company and a table named staff. There are two columns under this table with the name Name and StaffID. So this is the data that’s in the table.

Name    |   StaffID

admin   |   567

admin2 |   568

 

There are going to be 3 pages of code :

The 1st page for the login form,  –name of the file in this tutorial–>(dlogin.php)

The 2nd page for the page service(what service you are providing to your user), —> (dlogin2.php)

And the 3rd page for logout. —–>(dlogin3.php)

I didn’t set any password to connect to the database.

 

1st Page


<!DOCTYPE html>
<body>

<form action=”dlogin.php” method=”POST”>
<input type=”text” name=”user”>
<input type=”text” name=”pass”>
<input type=”submit” name=”submit”>
</form>

</body>
</html>

<?php

session_start();

$conn = mysqli_connect(“localhost”,”root”,””,”company”);

$user = $_POST[‘user’];

$pass = $_POST[‘pass’];

$select = “SELECT * FROM staff WHERE Name=’$user'”;

$retrieve = mysqli_query($conn,$select);

if(isset($_POST[‘submit’]))
{
while($row = mysqli_fetch_array($retrieve))
{
if($row[‘StaffID’]==$pass)
{
$_SESSION[‘login’]=$user;
header(“Location:dlogin2.php”);
}
else
{
echo “Wrong Password”;
}
}
}

?>


Explanation:

1. if(isset($_POST[‘submit’]))  {  }

  • If the submit button is pressed, then the code inside the {} will be executed.

 

 

 

 

2nd Page


<?php

session_start();

if(!isset($_SESSION[‘login’]))
{
header(“Location:dlogin.php”);
}

echo “Welcome, ” . $_SESSION[‘login’];

echo “<br><a href=’dlogin3.php’>LOGOUT</a>”;

?>


Explanation:

if(!isset($_SESSION[‘login’]))
{
header(“Location:dlogin.php”);
}

  • After you logout, try to go back to the dlogin2.php and see that it’ll automatically redirect you to dlogin.php. This piece of code does the job. It says if session login is not set, then go to dlogin.php. We set the session login to the username in dlogin.php. But then the session was destroyed when we logout. So now the value of session login is unset.

 

 

 

 

3rd Page


<?php

session_start();

if(session_destroy())
{
echo “Logout Successfully.”;
}

?>


 

So that is it for this post. It is difficult in the beginning, but the difficult part is what will make you understand. Do it many times until you can really understand it.

Any inquiries, mail me at imdad@zeroprogrammer.com.