Login and Logout using session in php and mysql Easy Method

Login using Session Variable:

Below is the Login page and we are going to create the session of username and password.

<?php 
$user=$_POST['user'];
$pass=$_POST['pass'];
$sql="select * from login where username=' ".$user." ' AND password=' ".$pass." ' ";
$result=mysql_query($sql);
if($row=mysql_fetch_array($result))
{
session_start();
$_SESSION['username']=$row['username'];
$_SESSION['password']=$row['password'];
header("Location:Home.php");
}

 }?>

Above code work as:

We accessed the data from data base ,if username and password that is enter by the user is correct then we will move to the Home.php  page.

"if($row=mysql_fetch_array($result))And if username and password is correct then will will create the session
For creating session first we will call the function session_start();
$_SESSION['username'] and $_SESSION['password'] are session variables that is save in the browser and by using this we can accessed different data from database on different pages...
As we know that the fetch username and password is in $row['username'], and $row['password'] so we assign session variable as ;

$_SESSION['username']=$row['username'];
$_SESSION['password']=$row['password'];


Now We are moving to Home Page Home.php

<?php
session_start();
if(!isset($_SESSION['username']&&$_SESSION['password'])
{
header("location:login.php");
}
$acc="select * from account where username='".$_SESSION['username']."' AND password='".$_SESSION['password']."' ";
$acc_res=mysql_query($acc);
$acc_row=mysql_fetch_array($acc_res);

?>

Above code work as:

If we have no session variable  $_SESSION['username'] AND $_SESSION['password'] Then header("location:login.php") will moves us back to the login.php page.
If we have session varaibles set then by using this we can accessed the values from the accounts table of user and user can use his/her profile or data or any thing  related.....


Learn What is cookie How to set Cookie for browser Click Here