Multi User Role Based Login in PHP with MySQL PDO - onlyxcodes

Thursday, 20 December 2018

Multi User Role Based Login in PHP with MySQL PDO

In this post, I will show you how to develop Multi User Role Based Login in PHP with MySQL PDO.


In our dynamic web application, the system provides security restrictions for users to log into their accounts based on their assigned roles and prevent unauthorized access.


We will make this system using PHP and MySQL are popular choices for web development, and we will use the PDO (PHP Data Objects) extension which provides a fast and consistent interface for accessing and managing databases in PHP applications.


The important thing is I built this project without any PHP frameworks such as Laravel, Codeigniter, or Cake PHP. I have used only the PHP core concept and built this project.


multi user role based login in php with mysql pdo

Table Content

1. Project Structure

2. Database and Table

3. connection.php

4. index.php [ PHP Login Form ]

    4.1 PHP Code For Login Form

    4.2 Login Codes Logic Explanation

5. register.php [ PHP Registration Form ]

    5.1 PHP Code For Registration Form

    5.2 Registration Codes Logic Explanation

6. admin_home.php

7. employee_home.php

8. user_home.php

9. logout.php


1. Project Structure

See the structure of the project directory inside C:\xampp\htdocs location below. Because I have the XAMPP server installed in C: drive.


Project Directory Structure of Multi User Role Based Login System

I created 7 files below for a multi user role based login system to develop completely.


1. connection.php


2. index.php


3. register.php


4. admin_home.php


5. employee_home.php


6. user_home.php


7. logout.php


2. Database and Table

To create a database and table, import and run below SQL code your PhpMyAdmin.


I have already inserted admin dumping records in a table here. Because this project only uses one super admin.


Note – The column in the table role field indicates the particular name of the role to be added by new users.

--
-- Database: `php_multiplelogin`
--

-- --------------------------------------------------------

--
-- Table structure for table `masterlogin`
--

CREATE TABLE `masterlogin` (
  `id` int(11) NOT NULL,
  `username` varchar(15) NOT NULL,
  `email` varchar(40) NOT NULL,
  `password` varchar(20) NOT NULL,
  `role` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;

--
-- Dumping data for table `masterlogin`
--

INSERT INTO `masterlogin` (`id`, `username`, `email`, `password`, `role`) VALUES
(11, 'hamid', '[email protected]', '123456', 'admin');

3. connection.php

I create a database connection in this file by the PDO extension of PHP.


<?php
$db_host="localhost"; //localhost server 
$db_user="root"; //database username
$db_password=""; //database password   
$db_name="php_multiplelogin"; //database name

try
{
 $db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
 $e->getMessage();
}

?>

4. index.php [ PHP Login Form ]

I created a login form in this file with two input boxes and one select option. The input box takes email and password, and the select option contains the role name admin, user, and employee which selects login access by specific role.


<form method="post" class="form-horizontal">
     
 <div class="form-group">
 <label class="col-sm-3 control-label">Email</label>
 <div class="col-sm-6">
 <input type="text" name="txt_email" class="form-control" placeholder="enter email" />
 </div>
 </div>
     
 <div class="form-group">
 <label class="col-sm-3 control-label">Password</label>
 <div class="col-sm-6">
 <input type="password" name="txt_password" class="form-control" placeholder="enter passowrd" />
 </div>
 </div>
     
 <div class="form-group">
 <label class="col-sm-3 control-label">Select Type</label>
 <div class="col-sm-6">
  <select class="form-control" name="txt_role">
   <option value="" selected="selected"> - select role - </option>
   <option value="admin">Admin</option>
   <option value="employee">Employee</option>
   <option value="user">User</option>
  </select>
 </div>
 </div>
    
 <div class="form-group">
 <div class="col-sm-offset-3 col-sm-9 m-t-15">
 <input type="submit" name="btn_login" class="btn btn-success" value="Login">
 </div>
 </div>
    
 <div class="form-group">
 <div class="col-sm-offset-3 col-sm-9 m-t-15">
 You don't have a account register here? <a href="register.php"><p class="text-info">Register Account</p></a>  
 </div>
 </div>
     
</form>

PHP Login Form Visually Below This Type :


PHP Login Form . Multi User Role Based Login in PHP with MySQL PDO





4.1 PHP Code for Login Form


Below PHP login codes responsible for identifying the user's authenticated email, password, and role name according to the specific role selection and verifying in the database. 


if all details are present in the table then the session will start according to the specific role name selection and roles will allow access to the own dashboard. otherwise, the required message will be displayed.


I know lengthy but not difficult move to logic code explanation below, you'll comprehend the full logic of the codes.


<?php
require_once 'connection.php';

session_start();

if(isset($_SESSION["admin_login"])) //check condition admin login not direct back to index.php page
{
 header("location: admin/admin_home.php"); 
}
if(isset($_SESSION["employee_login"])) //check condition employee login not direct back to index.php page
{
 header("location: employee/employee_home.php"); 
}
if(isset($_SESSION["user_login"])) //check condition user login not direct back to index.php page
{
 header("location: user/user_home.php");
}

if(isset($_REQUEST['btn_login'])) //login button name is "btn_login" and set this
{
 $email  =$_REQUEST["txt_email"]; //textbox name "txt_email"
 $password =$_REQUEST["txt_password"]; //textbox name "txt_password"
 $role  =$_REQUEST["txt_role"];  //select option name "txt_role"
  
 if(empty($email)){      
  $errorMsg[]="please enter email"; //check email textbox not empty or null
 }
 else if(empty($password)){
  $errorMsg[]="please enter password"; //check passowrd textbox not empty or null
 }
 else if(empty($role)){
  $errorMsg[]="please select role"; //check select option not empty or null
 }
 else if($email AND $password AND $role)
 {
  try
  {
   $select_stmt=$db->prepare("SELECT email,password,role FROM masterlogin
          WHERE
          email=:uemail AND password=:upassword AND role=:urole"); //sql select query
   $select_stmt->bindParam(":uemail",$email);
   $select_stmt->bindParam(":upassword",$password); //bind all parameter
   $select_stmt->bindParam(":urole",$role);
   $select_stmt->execute(); //execute query
     
   while($row=$select_stmt->fetch(PDO::FETCH_ASSOC)) //fetch record from MySQL database
   {
    $dbemail =$row["email"];
    $dbpassword =$row["password"];  //fetchable record store new variable they are "$dbemail","$dbpassword","$dbrole"
    $dbrole  =$row["role"];
   }
   if($email!=null AND $password!=null AND $role!=null) //check taken fields not null after countinue
   {
    if($select_stmt->rowCount()>0) //check row greater than "0" after continue
    {
     if($email==$dbemail AND $password==$dbpassword AND $role==$dbrole) //check type textbox email,password,role and fetchable record new variables are true after continue
     {
      switch($dbrole)  //role base user login start
      {
       case "admin":
        $_SESSION["admin_login"]=$email;   //session name is "admin_login" and store in "$email" variable
        $loginMsg="Admin... Successfully Login..."; //admin login success message
        header("refresh:3;admin/admin_home.php"); //refresh 3 second after redirect to "admin_home.php" page
        break;
        
       case "employee":
        $_SESSION["employee_login"]=$email;    //session name is "employee_login" and store in "$email" variable
        $loginMsg="Employee... Successfully Login...";  //employee login success message
        header("refresh:3;employee/employee_home.php"); //refresh 3 second after redirect to "employee_home.php" page
        break;
        
       case "user":
        $_SESSION["user_login"]=$email;    //session name is "user_login" and store in "$email" variable
        $loginMsg="User... Successfully Login..."; //user login success message
        header("refresh:3;user/user_home.php");  //refresh 3 second after redirect to "user_home.php" page
        break;
        
       default:
        $errorMsg[]="wrong email or password or role";
      }
     }
     else
     {
      $errorMsg[]="wrong email or password or role";
     }
    }
    else
    {
     $errorMsg[]="wrong email or password or role";
    }
   }
   else
   {
    $errorMsg[]="wrong email or password or role";
   }
  }
  catch(PDOException $e)
  {
   $e->getMessage();
  }  
 }
 else
 {
  $errorMsg[]="wrong email or password or role";
 }
}
?>



4.2 Login Codes Logic Explanation


Row no 2 – I included the configuration file of the database using the function require_once. Because we fire SQL select query for user login through $db database object.


Row no 4 – Using session_start() function we start the session.


Row no 6 to 17 – Three if conditions, get different roles name session keys (admin_login, employee_login, user_login). If both are found then the function header() sends the roles specific account.


This is the main objective of the session as the active login of any user will not directly access the login page their account required logout.


if(isset($_SESSION["admin_login"])) //check condition admin login not direct back to index.php page
{
 header("location: admin/admin_home.php"); 
}
if(isset($_SESSION["employee_login"])) //check condition employee login not direct back to index.php page
{
 header("location: employee/employee_home.php"); 
}
if(isset($_SESSION["user_login"])) //check condition user login not direct back to index.php page
{
 header("location: user/user_home.php");
} 

Row no 19 – If condition, get the name attribute value login form button btn_login using the method $_REQUEST[ ] array. And the isset() function targets this attribute value by clicking the event.


if(isset($_REQUEST['btn_login'])) //login button name is "btn_login" and set this 

Row no 21 to 23 – Using $_REQUEST [ ] variable method get all values txt_email, txt_password and txt_role by name attribute in the login form fields. Get able form fields all values store in created $email, $password & $role variables.


$email  =$_REQUEST["txt_email"]; //textbox name "txt_email"
$password =$_REQUEST["txt_password"]; //textbox name "txt_password"
$role  =$_REQUEST["txt_role"];  //select option name "txt_role" 

Row no 25 to 33 – three if and else if condition, empty() function checks that all variable value is not null.


if(empty($email)){      
 $errorMsg[]="please enter email"; //check email textbox not empty or null
}
else if(empty($password)){
 $errorMsg[]="please enter password"; //check passowrd textbox not empty or null
}
else if(empty($role)){
 $errorMsg[]="please select role"; //check select option not empty or null
}

Row no 34 – else if condition check each variable value returns true.


else if($email AND $password AND $role)

Row no 36 to 44 – Open the try / catch block, apply the select PDO query in the prepare() statement and select all records.


bindParam() function binds the value of the variables :uemail, :upassword and :urole in query place. And, above all, the values of $email, $password, and $role variables persist. execute() function execute the query statement. 


$select_stmt=$db->prepare("SELECT email,password,role FROM masterlogin
       WHERE
       email=:uemail AND password=:upassword AND role=:urole"); //sql select query
$select_stmt->bindParam(":uemail",$email);
$select_stmt->bindParam(":upassword",$password); //bind all parameter
$select_stmt->bindParam(":urole",$role);
$select_stmt->execute(); //execute query 

Row no 46 to 51 – PDOStatement:: fetch method returns row from the result set. PDO:: FETCH_ASSOC parameter informs PDO to return array value indexed by table column email, password and role. The $row is an array.


All values are stored created new variables $dbemail, $dbpassword and $dbrole.


while($row=$select_stmt->fetch(PDO::FETCH_ASSOC)) //fetch record from MySQL database
{
 $dbemail =$row["email"];
 $dbpassword =$row["password"];  //fetchable record store new variable they are "$dbemail","$dbpassword","$dbrole"
 $dbrole  =$row["role"];
} 

Row no 52 – if condition checks the variables $email, $password, and $role do not return null.


if($email!=null AND $password!=null AND $role!=null) //check taken fields not null after countinue 

Row no 54 – if condition test results the number of rows returnable by rowCount() function is greater than zero (>0).


if($select_stmt->rowCount()>0) //check row greater than "0" after continue 

Row no 56 – if condition, the user typeable form field values and table values must be matched using == operator check.


Note: – The == use of the operator for both operand values is equal to or not.


if($email==$dbemail AND $password==$dbpassword AND $role==$dbrole) //check type textbox email,password,role and fetchable record new variables are true after continue 

Row no 58 to 80 – Then the switch statement occurred, above all condition is true. And within the switch case statement, we store the values of the role name by the $dbrole variable since that variable holds the values of the role name that are already discussed above by the $row array.


switch($dbrole)  //role base user login start
{
 case "admin":
  $_SESSION["admin_login"]=$email;   //session name is "admin_login" and store in "$email" variable
  $loginMsg="Admin... Successfully Login..."; //admin login success message
  header("refresh:3;admin/admin_home.php"); //refresh 3 second after redirect to "admin_home.php" page
  break;
        
 case "employee":
  $_SESSION["employee_login"]=$email;    //session name is "employee_login" and store in "$email" variable
  $loginMsg="Employee... Successfully Login...";  //employee login success message
  header("refresh:3;employee/employee_home.php"); //refresh 3 second after redirect to "employee_home.php" page
  break;
        
 case "user":
  $_SESSION["user_login"]=$email;    //session name is "user_login" and store in "$email" variable
  $loginMsg="User... Successfully Login..."; //user login success message
  header("refresh:3;user/user_home.php");  //refresh 3 second after redirect to "user_home.php" page
  break;
        
 default:
 $errorMsg[]="wrong email or password or role";
} 

case "admin":   If the name of the admin role detected that case, assign the admin_login session key in $_SESSION[ ] array.


Apply the admin login message and the header() function will keep this message within 3 seconds, it will be sent in the admin_home.php page created under the admin folder and break it.


case "employee":   If the name of the employee role was found as the case became, assign employee_login session key in $_SESSION[ ] array.


Push login message for employees. The function header() keeps the message within 3 seconds, Send it to the employee_home.php page that was built in the employee folder and break it.


case "user":  When the user name was found as the case occurred, In $_SESSION[ ] array assign the session key name user_login.


Push user login message and keep the message in 3 seconds with header() function, send it to user_home.php page that was built in the user folder and break it.  


default: – The case statement of the switch provides the default state case. Attach error messages like wrong email or password or role inside the default case.


Note – I haven't explained else condition see any else condition detecting unique condition-based error message. And the error message is defined in the array variable $errorMsg[ ].

5. register.php [ PHP Registration Form ]


I have created the registration form for new user data to be registered in the database in this file.


This form contains three input boxes and one option to select. The three input boxes take username, email, and password, and the selection option takes the name of the role.


Look at the below registration form, which is responsible for adding role names to the database after selecting new users.


<form method="post" class="form-horizontal">
     
 <div class="form-group">
 <label class="col-sm-3 control-label">Userame</label>
 <div class="col-sm-6">
 <input type="text" name="txt_username" class="form-control" placeholder="enter username" />
 </div>
 </div>
    
 <div class="form-group">
 <label class="col-sm-3 control-label">Email</label>
 <div class="col-sm-6">
 <input type="text" name="txt_email" class="form-control" placeholder="enter email" />
 </div>
 </div>
     
 <div class="form-group">
 <label class="col-sm-3 control-label">Password</label>
 <div class="col-sm-6">
 <input type="password" name="txt_password" class="form-control" placeholder="enter passowrd" />
 </div>
 </div>
     
 <div class="form-group">
 <label class="col-sm-3 control-label">Select Type</label>
 <div class="col-sm-6">
  <select class="form-control" name="txt_role">
   <option value="" selected="selected"> - select role - </option>
   <option value="employee">Employee</option>
   <option value="user">User</option>
  </select>
 </div>
 </div>
    
 <div class="form-group">
 <div class="col-sm-offset-3 col-sm-9 m-t-15">
 <input type="submit"  name="btn_register" class="btn btn-primary " value="Register">
 </div>
 </div>
    
 <div class="form-group">
 <div class="col-sm-offset-3 col-sm-9 m-t-15">
 You have a account register here? <a href="index.php"><p class="text-info">Login Account</p></a>  
 </div>
 </div>
     
</form>

PHP Registration Form Visually Below This Type :


PHP Registration Form . Multi User Role Based Login in PHP with MySQL PDO

5.1 PHP Code For Registration Form


Below are PHP codes that register new user data to the database. Validation is also provided in these codes and if you have already registered username or user email, the message would indicate the email or username already exists.


Extra these codes validate the right email format and the length of the password must be 6 characters. It will handle the registration process along with suitable validation.


The below codes are long but not complicated jump to the explanation of the logic codes so you can easily comprehend the logic.




<?php

require_once "connection.php";

if(isset($_REQUEST['btn_register'])) //check button name "btn_register" and set this
{
 $username = $_REQUEST['txt_username']; //textbox name "txt_username"
 $email  = $_REQUEST['txt_email']; //textbox name "txt_email"
 $password = $_REQUEST['txt_password']; //textbox name "txt_password"
 $role  = $_REQUEST['txt_role']; //select option name "txt_role"
  
 if(empty($username)){
  $errorMsg[]="Please enter username"; //check username textbox not empty or null
 }
 else if(empty($email)){
  $errorMsg[]="Please enter email"; //check email textbox not empty or null
 }
 else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
  $errorMsg[]="Please enter a valid email address"; //check proper email format 
 }
 else if(empty($password)){
  $errorMsg[]="Please enter password"; //check passowrd textbox not empty or null
 }
 else if(strlen($password) < 6){
  $errorMsg[] = "Password must be atleast 6 characters"; //check passowrd must be 6 characters
 }
 else if(empty($role)){
  $errorMsg[]="Please select role"; //check not select role 
 }
 else
 { 
  try
  { 
   $select_stmt=$db->prepare("SELECT username, email FROM masterlogin 
          WHERE username=:uname OR email=:uemail"); // sql select query
   $select_stmt->bindParam(":uname",$username);   
   $select_stmt->bindParam(":uemail",$email);      //bind parameters
   $select_stmt->execute();
   $row=$select_stmt->fetch(PDO::FETCH_ASSOC); //execute query and fetch record store in "$row" variable
   
   if($row["username"]==$username){
    $errorMsg[]="Sorry username already exists"; //check new user type username already exists or not in username textbox
   }
   else if($row["email"]==$email){
    $errorMsg[]="Sorry email already exists"; //check new user type email already exists or not in email textbox
   }
   
   else if(!isset($errorMsg))
   {
    $insert_stmt=$db->prepare("INSERT INTO masterlogin(username,email,password,role) VALUES(:uname,:uemail,:upassword,:urole)"); //sql insert query     
    $insert_stmt->bindParam(":uname",$username); 
    $insert_stmt->bindParam(":uemail",$email);     //bind all parameter 
    $insert_stmt->bindParam(":upassword",$password);
    $insert_stmt->bindParam(":urole",$role);
    
    if($insert_stmt->execute())
    {
     $registerMsg="Register Successfully.....Wait Login page"; //execute query success message
     header("refresh:4;index.php"); //refresh 4 second and redirect to index.php page
    }
   }
  }
  catch(PDOException $e)
  {
   echo $e->getMessage();
  }
 }
}
?>



5.2 Registration Codes Logic Explanation


Row no 3 – I added the connection file to the database using the require_once function. Via the database file object $db, I applied PDO queries.


Row no 5 – This If condition, uses the method $_REQUEST[ ] array to get the name attribute value registration form button btn_register, and the isset() function targets the value of this attribute by clicking on the event.


if(isset($_REQUEST['btn_register'])) //check button name "btn_register" and set this 

Row no 7 to 10 – Using the $_REQUEST[ ] array method we get all txt_username, txt_email, txt_password, and txt_role values by name attribute in the fields of the registration form. Get form fields that store all values in created variables $username, $email, $password & $role.


$username = $_REQUEST['txt_username']; //textbox name "txt_username"
$email  = $_REQUEST['txt_email']; //textbox name "txt_email"
$password = $_REQUEST['txt_password']; //textbox name "txt_password"
$role  = $_REQUEST['txt_role']; //select option name "txt_role" 

Row no 12 to 29 – This If and else condition verifies the form field values are not null using the function empty(). As well as checking valid email address format and password length at least 6 characters must be needed.


filter_var – Filter a variable with a specified filter.


FILTER_VALIDATE_EMAIL –  The FILTER_VALIDATE_EMAIL filter validates an e-mail address ( according to php.net ).


I filter $email variable value here that is taken from user input to check valid email address format.


strlen() – Returns the length of the given string. ( according to php.net ).


Here I checked the variable value of $password that takes user inputs less than six (< 6) or not.


if(empty($username)){
 $errorMsg[]="Please enter username"; //check username textbox not empty or null
}
else if(empty($email)){
 $errorMsg[]="Please enter email"; //check email textbox not empty or null
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
 $errorMsg[]="Please enter a valid email address"; //check proper email format 
}
else if(empty($password)){
 $errorMsg[]="Please enter password"; //check passowrd textbox not empty or null
}
else if(strlen($password) < 6){
 $errorMsg[] = "Password must be atleast 6 characters"; //check passowrd must be 6 characters
}
else if(empty($role)){
 $errorMsg[]="Please select role"; //check not select role 
} 

Row no 32 to 39 – Inside the try / catch block discussion. Apply PDO select query under the prepare() statement and a select username and email values from the table.


bindParam() function bind the parameter :uname, :uemail values placed within select query. And both values consistent by $username and $email variables. The function execute() executes a PDO query statement.


PDOStatement:: fetch method extracts a row from the set of results. PDO:: FETCH_ASSOC parameter tells PDO to retrieve array value indexed by username and email of the table column. The array is $row.


$select_stmt=$db->prepare("SELECT username, email FROM masterlogin 
       WHERE username=:uname OR email=:uemail"); // sql select query
$select_stmt->bindParam(":uname",$username);   
$select_stmt->bindParam(":uemail",$email);      //bind parameters
$select_stmt->execute();
$row=$select_stmt->fetch(PDO::FETCH_ASSOC); //execute query and fetch record store in "$row" variable 

Row no 41 to 46 – If and if-else condition checks the new user has entered the username and the email value already exists from the table or not.


if($row["username"]==$username){
 $errorMsg[]="Sorry username already exists"; //check new user type username already exists or not in username textbox
}
else if($row["email"]==$email){
 $errorMsg[]="Sorry email already exists"; //check new user type email already exists or not in email textbox
} 

Row no 48 to 60 – else if condition, the isset() function checks that the $errorMsg variable does not return any error message, and applies the PDO insert query in prepare() statement.

The function bindParam() binds the values :uname, :uemail, :upassword and :urole in the insert query. All parameter values carry variables along with $username, $email, $password, and $role.


Finally, the execute() function executes the insert query statement, displays the register successfully message and the header() function keeps this message at 4 seconds and sends it to index.php page.


else if(!isset($errorMsg))
{
    $insert_stmt=$db->prepare("INSERT INTO masterlogin(username,email,password,role) VALUES(:uname,:uemail,:upassword,:urole)"); //sql insert query     
    $insert_stmt->bindParam(":uname",$username); 
    $insert_stmt->bindParam(":uemail",$email);     //bind all parameter 
    $insert_stmt->bindParam(":upassword",$password);
    $insert_stmt->bindParam(":urole",$role);
    
    if($insert_stmt->execute())
    {
  $registerMsg="Register Successfully.....Wait Login page"; //execute query success message
  header("refresh:4;index.php"); //refresh 4 second and redirect to index.php page
    }
}

6. admin_home.php

Row no 8 – Verify that the admin session key admin_login has not been found then returns the header() function onto the index page. Because the admin role does not have direct access to the admin page. The session key is confirmation from the index/login form that the admin is authenticated. 


Row no 13 – This condition checks whether the employee's role session key employee_login is found then the header() function sends to the employee_home.php page. Because the admin page doesn't allow permissions employee role to access this page.


Row no 18 – Also this condition works above, if the user's role user_login session key is found then the function header() delivers to the user_home.php page. The user role does not access the admin page because permissions were still not allowed on this page.


Row no 23 to 29 – Get admin_login session key to admin role and view e-mail admin value using echo.


<center>
 <h1>Admin Page</h1>
    
 <h3>
 <?php
  session_start();

  if(!isset($_SESSION['admin_login'])) //check unauthorize user not direct access in "admin_home.php" page
  {
   header("location: ../index.php");  
  }

  if(isset($_SESSION['employee_login'])) //check employee login user not access in "admin_home.php" page
  {
   header("location: ../employee/employee_home.php"); 
  }

  if(isset($_SESSION['user_login'])) //check user login user not access in "admin_home.php" page
  {
   header("location: ../user/user_home.php");
  }
  
  if(isset($_SESSION['admin_login']))
  {
  ?>
   Welcome,
  <?php
   echo $_SESSION['admin_login'];
  }
  ?>
 </h3>
  <a href="../logout.php">Logout</a>
</center>

Admin Account Visually Below This Type :


admin account

7. employee_home.php

Row no 9 – Here scan the employee_login session key of the employee role that was not found then sending the header() function on the index page.


Row no 14 – Here we get admin_login session key if you find sending by header function to admin_home.php page. Because the employee account has not allowed admin permissions to access this page.


Row no 19 – The same here we get user_login session key of user role if we consider sending by header() function to user_home.php page. Not to access the employee account or page, either, the user role.


Row no 24to 30 – Take employee_login session key of employee role and use echo to display employee email address value.




<center>
 <h1>Employee Page</h1>
    
 <h3>
 <?php
    
 session_start();

 if(!isset($_SESSION['employee_login'])) //check unauthorize user not direct access in "employee_home.php" page
 {
  header("location: ../index.php");
 }

 if(isset($_SESSION['admin_login'])) //check admin login user not access in "employee_home.php" page
 {
  header("location: ../admin/admin_home.php");
 }

 if(isset($_SESSION['user_login'])) //check user login user not access in "employee_home.php" page
 {
  header("location: ../user/user_home.php");
 }
    
 if(isset($_SESSION['employee_login']))
 {
 ?>
  Welcome,
 <?php
  echo $_SESSION['employee_login'];
 }
 ?>
 </h3>
  <a href="../logout.php">Logout</a>
</center>

Employee Account Visually Below This Type :


employee account

8. user_home.php

Row no 9 – We apply admin and employee page account tactics on this page. We get user_login session key of user role, if not found then the header() function transfers immediately to the index page because any user role does not directly access the user account.


Row no 14 – In this condition we obtain the admin_login session key of the admin role if it is detected then sending by header() function to the admin account.


Row no 19 – Exactly here we use the same techniques of the above condition in this condition. We receive employee_login session key of employee role if find then deliver by header() function to employee account.


Row no 24 to 30 – Finally, accept user_login session key of user role and use echo to display active user login email address.




<center>
 <h1>User Page</h1>
    
 <h3>
 <?php
    
 session_start();

 if(!isset($_SESSION['user_login'])) //check unauthorize user not direct access in "user_home.php" page
 {
  header("location: ../index.php");
 }

 if(isset($_SESSION['admin_login'])) //check admin login user not access in "user_home.php" page
 {
  header("location: ../admin/admin_home.php");
 }

 if(isset($_SESSION['employee_login'])) //check employee login user not access in "employee_home.php" page
 {
  header("location: ../employee/employee_home.php");
 }

 if(isset($_SESSION['user_login']))
 {
 ?>
  Welcome,
 <?php
  echo $_SESSION['user_login'];
 }
 ?>
 </h3>
  <a href="../logout.php">Logout</a>
</center>

User Account Visually Below This Type :


user account

9. logout.php

In this file, along with click logout hyperlink, we destroy the session from the whole role's account and send it all to the index/login page.




<?php
session_start();

header("location:index.php");

session_destroy();

?>

Learn More PDO Tutorials:

How to upload an image to a database using PHP PDO

How to Upload, Insert, Update and Delete File Using PHP PDO & MySQL

Add to Cart and Checkout Code in PHP PDO

Login and Register Script In PHP PDO With MySQL

Multiple Checkbox Value Add, Edit, Delete using PHP PDO with MySQL

76 comments:

  1. is it ok to send me to source code of this document?

    ReplyDelete
  2. error message not displaying

    ReplyDelete
  3. These Codes Paste before form tag all error messages are displaying perfectly.

    <?php
    if(isset($errorMsg))
    {
    foreach($errorMsg as $error)
    {
    echo $error;
    }
    }
    if(isset($loginMsg))
    {
    echo $loginMsg;
    }

    ReplyDelete
  4. where is source code where is download link

    ReplyDelete
  5. Hi Vivek currently I not put source codes zip file of this tutorial. But see all codes I explain properly. If you face any issue about this tutorial codes then contact me.

    ReplyDelete
    Replies
    1. can you email source code zip

      Delete
    2. Hi, currently I'm not sharing this tutorial source code.
      If you face any issue then contact me.

      Delete
  6. hye.. i have problem with the coding.. as i login, it does not function well and it kind like refresh..why is it like that?

    ReplyDelete
  7. Check your login codes all accessories like button name attribute click event, text box name attribute, select query, folder path location etc. This project works properly.

    ReplyDelete
  8. Nice Article Sir, I will try this code. Thank you.

    ReplyDelete
  9. Hi, Currently I totally disabled copy everything from this page and download link. If you face any issue about this project contact me.

    ReplyDelete
  10. Can i get source code for academic issues, please.

    ReplyDelete
    Replies
    1. Sorry, I closed the download link for personal reasons.

      Delete
  11. please. I need help. I do all things you show but still I got an error and it say.."SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens". I treid to search to goggle but then not work. I lost how many recheck that I did...my email [email protected]. Please help me Sir.

    ReplyDelete
    Replies
    1. Hi, all codes are work perfectly, please check your queries and bind parameter variables.

      Delete
    2. Thank You so Much for this great help. Really appreciate.

      Delete
  12. hey i get this error message

    SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1

    how do i fix it

    ReplyDelete
    Replies
    1. which page you got this error message, show your codes because all codes are perfectly worked

      Delete
  13. I started coding ...but stuck. Login form is not visually apeared after running the code. Please help how to merge both codes of login form appearance and validating the login info.
    Please guide me

    ReplyDelete
    Replies
    1. All codes are work perfectly, please follow my explanation.

      Second thought, I used bootstrap to design the login form and also applied validation through login codes and all validation visually displayed by bootstrap alert messages.

      Delete
  14. How to allow the admin to view the employee's role pages too ?

    ReplyDelete
    Replies
    1. Remove below condition on the employee page, then admin allows to show employee page

      if(isset($_SESSION['admin_login']))
      {
      header("location: ../admin/admin_home.php");
      }

      Delete
  15. Tried copy all the codes provided by you.
    Login Page is responding
    Error getting while registration --- SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected

    ReplyDelete
    Replies
    1. Apparently the database in your DSN string is case sensitive. It should be dbname.

      Delete
  16. Hello Hamid,
    I'm trying to login to multiple users but i cannot login. please help me. below is my code
    prepare("SELECT userName, password, roleType FROM users WHERE userName=:uname AND password=:upassword AND roleType=:uroleType");

    $select_stmt->bindParam(":uname", $userName);
    $select_stmt->bindParam(":upassword", $password);
    $select_stmt->bindParam(":uroleType", $roleType);
    $select_stmt->execute(); //execute query

    while($row=$select_stmt->fetch(PDO::FETCH_ASSOC)) //fetch records from database
    {
    //fetchable records store new variables
    $connuserName = $row["userName"];
    $connpassword = $row["password"];
    $connroleType = $row["roleType"];

    }

    if($userName != null AND $password != null AND $roleType !=null ) //check taken fields
    {
    if($select_stmt->rowCount() > 0) //check row greater zero
    {
    if($userName == $connuserName AND $password == $connpassword AND $roleType == $connroleType)
    {

    switch($connroleType)
    {
    case "Admin":
    $_SESSION["admin_login"] = $userName;
    $loginMsg = "Admin .... Successfully login";
    header("refresh:3; admin-dashboard.php");
    break;

    case "Doctor":
    $_SESSION["doctor_login"] = $userName;
    $loginMsg = "Doctor .... Successfully ...";
    header("refresh:3; doctor-dashboard.php");
    break;

    case "Patient":
    $_SESSION["patient_login"] = $userName;
    $loginMsg = "Patient..... Successfully login...";
    header("refresh:3; patient-dashboard.php");
    break;

    default:
    $errorMsg[] = "Wrong username or password or role";
    }

    }
    else{
    $errorMsg[] = "Wrong username or password or role";
    }
    }else {
    $errorMsg[] = "Wrong username or password or role";
    }
    } else {
    $errorMsg[] = "Wrong username or password or role";
    }

    }
    catch(PDOException $e)
    {
    $e->getMessage();
    }

    }
    else{
    $errorMsg[] = "Wrong username or password or role";
    }
    }

    ?>

    ReplyDelete
    Replies
    1. Your code is half. please follow my full codes instruction guidelines focus on session and other factor

      Delete
  17. good day sir. i want to login user immediately after registration. this the code have but working.
    prepare("SELECT userName, email FROM users WHERE userName=:uname OR email=:uemail");

    $select_stmt->bindParam(":uname",$userName);
    $select_stmt->bindParam(":uemail",$email);
    $select_stmt->execute();
    $row = $select_stmt->fetch(PDO::FETCH_ASSOC);


    if($row["userName"] == $userName){
    $errorMsg[] = "Sorry username exist";
    }elseif($row["email"] == $email){
    $errorMsg[] = "Sorry email exist";
    }elseif($row["password"] == $password){
    $errorMsg[] = "Sorry password has already been taken";
    }
    elseif(count($errorMsg) === 0){

    $password = password_hash($password, PASSWORD_DEFAULT);
    $token = bin2hex(random_bytes(50));
    $verified = false;

    $insert_stmt = $conn->prepare("INSERT INTO users(userName, email, roleType, verified, token, password) VALUES(:uname, :uemail, :uroleType, :uverified, :utoken, :upassword)");
    $insert_stmt->bindParam(":uname", $userName);
    $insert_stmt->bindParam(":uemail", $email);
    $insert_stmt->bindParam(":uroleType", $roleType);
    $insert_stmt->bindParam(":uverified", $verified);
    $insert_stmt->bindParam(":utoken", $token);
    $insert_stmt->bindParam(":upassword", $password);

    if($insert_stmt->execute()){
    $registerMsg = "Register Successfully ... ";

    //login User immediately
    $user_id = $conn->insert_id;
    $_SESSION['id'] = $user_id;
    $_SESSION['userName'] = $userName;
    $_SESSION['email'] = $email;
    $_SESSION['verified'] = $verified;
    $_SESSION['roleType'] = $roleType;

    //redirect to dashboard
    $roleType = $_SESSION['roleType'];
    switch($roleType){
    case 'Doctor':
    header('location:doctor-dashboard.php');
    break;
    case 'Patient':
    header('location:patient-dashboard.php');
    break;
    case 'Admin':
    header('location:admin-dashboard.php');
    break;

    default:
    $errorMsg['db_error'] = 'Database error: failed to register user';

    }
    }
    }

    }
    catch(PDOException $e)
    {
    echo $e->getMessage();
    }
    }
    }

    ?>

    ReplyDelete
  18. ive done everything as you've displayed but the error messages do not show up on the forms. also the register/login buttons just refresh the page but do not enter anything into the database. some help please?

    ReplyDelete
    Replies
    1. These codes paste before form tag all error message are displaying perfectly.
      <?php
      if (isset($errorMsg))
      {
      foreach($errorMsg as $error)
      {
      echo $error;
      }
      }
      if(isset($loginMsg))
      {
      echo $loginMsg;
      }

      And, check your button attribute name properly if match then button click event work perfectly register and login activity

      Delete
  19. Good day sir, I have problem regarding this coding. It seems that I need to press the Login button twice before I can login into the system. Is there any way to fix it?

    ReplyDelete
    Replies
    1. No needed to fix, all codes are working perfectly, keep follow the code structure

      Delete
  20. i have a problem with logging in. everything checks out but it just refreshes i used different variables because im using it for a school project. this is my code:require_once 'connection.php';

    session_start();

    if(isset($_SESSION["Opdrachtgever_login"]))
    {
    header("location: Opdrachtgever.php");
    }
    if(isset($_SESSION["Student_login"]))
    {
    header("location: Student.php");
    }
    if(isset($_SESSION["Docent_login"]))
    {
    header("location: Docent.php");
    }

    if(isset($_REQUEST['btn_login']))
    {
    $email = $_REQUEST["txt_email"];
    $wachtwoord = $_REQUEST["txt_wachtwoord"];
    $account_rol = $_REQUEST["txt_account_rol"];

    if(empty($email)){
    $errorMsg[]="please enter email";
    }
    else if(empty($wachtwoord)){
    $errorMsg[]="please enter Password";
    }
    else if(empty($account_rol)){
    $errorMsg[]="please enter role";
    }
    else if($email AND $wachtwoord AND $account_rol)
    {
    try
    {
    $select_stmt=$db->prepare("SELECT email, wachtwoord, account_rol FROM accounts where email=:uemail AND wachtwoord=:uwachtwoord AND account_rol=:uaccount_rol");
    $select_stmt->bindParam(":uemail",$email);
    $select_stmt->bindParam(":uwachtwoord",$wachtwoord);
    $select_stmt->bindParam(":uaccount_rol",$account_rol);

    while($row=$select_stmt->fetch(PDO::FETCH_ASSOC))
    {
    $dbemail = $row["email"];
    $dbwachtwoord = $row["wachtwoord"];
    $dbaccount_rol = $row["account_rol"];
    }
    if($email!=null AND $wachtwoord!=null AND $account_rol!=null)
    {
    if($select_stmt->rowCount()>0)
    {
    if($email==$dbemail AND $wachtwoord==$dbwachtwoord AND $account_rol==$dbaccount_rol)
    {
    switch($dbaccount_rol)
    {

    case "Opdrachtgever":
    $_SESSION["Opdrachtgever_login"]=$email;
    $loginMsg="Opdrachtgever... Succesvol ingelogd!";
    header("refresh:3; Opdrachtgever.php");
    break;

    case "Docent":
    $_SESSION["Docent_login"]=$email;
    $loginMsg="Docent... Succesvol ingelogd!";
    header("refresh:3; Docent.php");
    break;

    case "Student":
    $_SESSION["Student_login"]=$email;
    $loginMsg="Student... Succesvol ingelogd!";
    header("refresh:3; Student.php");
    break;

    default:
    $errorMsg[]="Verkeerde email, wachtwoord of account rol";
    }
    }
    else
    {
    $errorMsg[]="wrong email or password or role";
    }
    }
    else
    {
    $errorMsg[]="wrong email or password or role";
    }
    }
    else
    {
    $errorMsg[]="wrong email or password or role";
    }
    }
    catch(EXCEPTION $e)
    {
    $e->getMessage();
    }
    }
    else
    {
    $errorMsg[]="Verkeerde email, wachtwoord of account rol";
    }
    }

    ReplyDelete
    Replies
    1. Hi, check your login button name attribute value must match with "btn_login".

      Delete
  21. hello sir, how to create md5 password?

    ReplyDelete
    Replies
    1. Hi Zailir Othman, the md5() is out dated. I suggest you use password_hash() function to generate secure password than md5().

      Read my this article https://www.onlyxcodes.com/2019/04/login-and-register-script-in-php-pdo.html I have used.

      Thank you.

      Delete
    2. Welcome Zailir Othman keep visiting and like on Facebook.

      Delete
  22. Replies
    1. Hi, all codes are work perfectly. Check again your code if found any issue then connect me I will solve your issue

      Delete
  23. Replies
    1. Hi, currently I disabled everything to copy code, please follow codes explanation if you have any issue then contact me.

      Thank you.

      Delete
  24. I have done everything but the error massage is not work and i cant register and login the pages just refresh what maybe the problem

    ReplyDelete
  25. Thank You Hamid for giving the source. All are working but The error messages are not displayed.
    default:
    $errorMsg[]="wrong email or password or role";
    }
    }
    else
    {
    $errorMsg[]="wrong email or password or role";
    }
    }
    else
    {
    $errorMsg[]="wrong email or password or role";
    }
    }
    else
    {
    $errorMsg[]="wrong email or password or role";
    }
    }
    catch(PDOException

    and also the validation part

    if(isset($_REQUEST['btn_login'])) //login button name is "btn_login" and set this
    {
    $email =$_REQUEST["txt_email"]; //textbox name "txt_email"
    $password =$_REQUEST["txt_password"]; //textbox name "txt_password"
    $role =$_REQUEST["txt_role"]; //select option name "txt_role"

    if(empty($email)){
    $errorMsg[]="please enter email"; //check email textbox not empty or null
    }
    else if(empty($password)){
    $errorMsg[]="please enter password"; //check passowrd textbox not empty or null
    }
    else if(empty($role)){
    $errorMsg[]="please select role"; //check select option not empty or null
    }
    else if($email AND $password AND $role)
    {


    Please advise.

    ReplyDelete
    Replies
    1. Hi,

      These Codes Paste before form tag all error messages are displaying perfectly.

      <?php
      if(isset($errorMsg))
      {
      foreach($errorMsg as $error)
      {
      echo $error;
      }
      }

      if(isset($loginMsg))
      {
      echo $loginMsg;
      }

      Delete
  26. Hi sir. This is a useful tutorial. But i can't login. It just refresh after i click login button but doesnt show the next page.

    ReplyDelete
    Replies
    1. check your login button name attribute value must match with btn_login

      Delete
  27. hello sir. may i ask if this php code is object oriented or structured? Thanks

    ReplyDelete
    Replies
    1. object oriented is most important part of every programming language. The PHP also has OOPS programming.

      Delete
  28. I'm getting this error

    Notice: Undefined index: txt_username in C:\xampp\htdocs\multiplelogin\register.php on line 7

    what should i do?

    ReplyDelete
    Replies
    1. check your register.php file username text box name attribute value must match with txt_username

      Delete
  29. Hi, i got this error after click on sign in button (Parse error: syntax error, unexpected 'catch' (T_CATCH) in C:\xampp\htdocs\nwm\dbloginpage.php on line 101) can u help me

    ReplyDelete
  30. hi, can u email me the full source code

    ReplyDelete
    Replies
    1. Sorry, this source code not allow this time

      Delete
  31. I got this error

    Fatal error: Function name must be a string in C:\wamp\www\apex-admin\Administrator\register.php on line 5

    ReplyDelete
    Replies
    1. please, follow source code instruction step by step

      Delete
  32. Sir I have gotten an error.

    Error: Parse error: syntax error, unexpected token "else" in C:\Users\brand\OneDrive\Desktop\XAMAPP\htdocs\Water Tower 2000\index.php on line 139

    Code:

    prepare("SELECT email,password,role FROM masterlogin WHERE email=:uemail

    AND password=:upassword AND role=:urole");




    $select_stmt->bindParam(":uemail",$email);

    $select_stmt->bindParam(":upassword",$password);

    $select_stmt->bindParam(":uemail",$role);

    $select_stmt->excute();





    while ($row=$select_stmt->fetch(PDO::FETCH_ASSOC)){

    $dbemail =$row["email"];

    $dbpassword =$row["password"];

    $dbrole =$row["role"];

    }



    if($email!=null AND $password!=null AND $role!=null){





    if($select_stmt->rowCount()>0){



    if ($email!==$dbemail AND $password==$dbpassword AND $role==$dbrole){



    switch($dbrole) {



    case "admin":

    $_SESSION ["admin_login"]=$email;

    $loginMsg="Admin...Your in Water Tower...";

    header("refresh:3;admin/admin_home.php");

    break;



    case "parent":

    $_SESSION["parent_login"]=$email;

    $loginMsg="Parent...Welcome To Water Tower...";

    header("refresh:3;parent/parent_home.php");

    break;




    case "swimmer":

    $_SESSION ["swimmer_login"]=$email;

    $loginMsg="Fellow swimmer...Your in Water Tower...";

    header("refresh:3;swimmer/swimmer_home.php");

    break;



    default:

    $errorMsg[]="Sorry but either the email/password/role is wrong";

    }

    }



    else {

    $errorMsg="Sorry but either the email/password/role is wrong";

    }

    }



    else {

    $errorMsg="Sorry but either the email/password/role is wrong";



    }



    }



    else{

    $errorMsg="Sorry but either the email/password/role is wrong";

    }

    }



    catch (PDOException $e){



    $e->getMassage();

    }

    }

    else {

    $errorMsg="Sorry but either the email/password/role is wrong";

    }

    }

    ?>

    ReplyDelete
    Replies
    1. You write $select_stmt->bindParam(':uemail', $role);

      please change below

      $select_stmt->bindParam(':urole', $role);

      Delete
  33. Thanks but I still have the error. Anything else

    ReplyDelete
  34. Sir apparently you need a corresponding if to use else but from 82 to 96 there seem to be no if for the else could you explain that to me sir.

    ReplyDelete
    Replies
    1. Look 82 to 96, they all are else condition of specific if. Those are shows specific error messages

      Delete
  35. Sir, I've finally solved the issue I had, however I have an new problem.

    When I tried to log on I got these warnings:

    Warning: Undefined array key "txt_email"
    Warning: Undefined array key "txt_password"
    Warning: Undefined array key "txt_role"

    I tried to change $_REQUEST to $_COOKIE and that got rid of the errors, however when I tried to log in it didn't go to the next page. What should I do?

    Full code:

    prepare("SELECT email,password,role FROM masterlogin WHERE email=:uemail

    AND password=:upassword AND role=:urole");

    $select_stmt->bindParam(":uemail",$email);

    $select_stmt->bindParam(":upassword",$password);

    $select_stmt->bindParam(":urole",$role);

    $select_stmt->excute();

    while ($row=$select_stmt->fetch(PDO::FETCH_ASSOC)){

    $dbemail =$row["email"];

    $dbpassword =$row["password"];

    $dbrole =$row["role"];

    }

    if($email!=null AND $password!=null AND $role!=null){

    if($select_stmt->rowCount()>0){

    if ($email!==$dbemail AND $password==$dbpassword AND $role==$dbrole){

    switch($dbrole) {

    case "admin":

    $_SESSION ["admin_login"]=$email;
    $loginMsg="Admin...Your in Water Tower...";
    header("refresh:3;admin/admin_home.php");
    break;

    case "parent":
    $_SESSION["parent_login"]=$email;
    $loginMsg="Parent...Welcome To Water Tower...";
    header("refresh:3;parent/parent_home.php");
    break;

    case "swimmer":
    $_SESSION ["swimmer_login"]=$email;
    $loginMsg="Fellow swimmer...Your in Water Tower...";
    header("refresh:3;swimmer/swimmer_home.php");
    break;

    default:
    $errorMsg[]="Sorry but either the email/password/role is wrong";
    }

    }



    else {

    $errorMsg="Sorry but either the email/password/role is wrong";
    }

    }

    else {

    $errorMsg="Sorry but either the email/password/role is wrong";

    }

    }

    else{

    $errorMsg="Sorry but either the email/password/role is wrong";

    }

    }



    catch (PDOException $e){

    $e->getMassage();

    }

    }

    else {

    $errorMsg="Sorry but either the email/password/role is wrong";

    }

    }

    ?>

    ReplyDelete
    Replies
    1. Check your login form all fields name attribute values

      Delete
  36. In my SQL I get " SELECT * FROM 'masterlogin' WHERE 1" is that okay?

    ReplyDelete
    Replies
    1. I recommended you please follow line by line whole codes. A specific code not identify what you say

      Delete
  37. Just one thing sir. My login system does not work when I try to log on it doesn't go to the next page it just stays at the same page.

    ReplyDelete
    Replies
    1. All codes work perfectly please follow source code line by line

      Delete
  38. Sir when I try to log on my login system stays at the same page.

    ReplyDelete
    Replies
    1. The login codes work perfectly. I recommended you please follow line by line source code

      Delete
  39. Sir in my register.phpI seem to be getting error: Parse error: syntax error, unexpected token "echo" in C:\Users\brand\OneDrive\Desktop\XAMAPP\htdocs\Water Tower 2000\register.php on line 58
    Do you know whats wrong?

    Php Code:

    prepare("SELECT username,email FROM masterlogin WHERE username=:uname OR
    email=:uemail");

    $select_stmt->bindParam(":uname",$username);
    $select_stmt->bindParam(":uemail",$email);
    $select_stmt->excute();
    $row=$select_stmt->fetch(PDO::FETCH_ASSOC);


    if ($row["username"]==$username){
    $errorMsg[]="Sorry but username already exsit";
    }

    else if ($row["email"]==$email){
    $errorMsg[]="Sorry but email already exsit";
    }

    else if(!$isset($errorMsg)){

    $insert_stmt=$db->prepare ("INSERT INTO masterlogin (username,email,password,root) VALUES(:uname,:uemail,:upassword,:urole)");
    $insert_stmt->bindParam(":uname",$username);
    $insert_stmt->bindParam("uemail",$uemail);
    $insert_stmt->bindParam("upassword",$upassword);
    $insert_stmt->bindParam("urole",$role);

    if($insert_stmt->excute()) {

    $registerMsg = "Register Succesfully...Wait Login Page";
    header("refresh:4;index.php");

    }

    }

    }


    catch (PDOException $e) {

    echo $e->getMassage();

    }

    }

    }

    ?>

    ReplyDelete
    Replies
    1. your code is half, I recommended you please follow register codes line by line

      Delete

Post Bottom Ad