1

I am trying to make a login form which is able to detect whether the user is admin or non-admin. I tried the following but when i run it i get no results:

<?php

    session_start();
    $message = "";

    if(count($_POST)>0)
    {
        $conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));

        ((bool)mysqli_query($conn, "USE prosoftl_rcc"));

        $result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
        $row  = mysqli_fetch_array($result);

        $a = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
        $r = mysqli_fetch_array($a);

        if(is_array($row))
        {
            $_SESSION["id"] = $row[id];
            $_SESSION["name"] = $row[name];
        }
        elseif(is_array($r))
        {
            $_SESSION["admin"] = $row[id];
        }
        else
        {
            $message = "Invalid Username or Password!";
        }
    }
    if(isset($_SESSION["id"]))
    {
        header("Location:user_dashboard.php");
    }
    elseif(isset($_SESSION["admin"]))
    {
        header ("location:gui-admin.php");
    }

?>

When i insert the username and password for admin it reloads the login form.

UPDATE 1:

The non-admin part is just working fine but the admin part redirects/reloads itself to the login form.

akmozo
  • 9,829
  • 3
  • 28
  • 44
Bhaamb
  • 91
  • 1
  • 10

5 Answers5

0

you should check your login post form,should have a code like this:

<form name="loginform" method="post" action="check.php">

if your 'action' vlaue is invalid,the page may refresh.

you should confirm that your login form is posted to the php page you posted.

0

Try this, lets see what happens.

session_start();
$msg = "";
if(count($_POST)>0){
 $conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));

    ((bool)mysqli_query($conn, "USE prosoftl_rcc"));

    $result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
    $stdCount  = mysqli_num_rows($result);//counts the number or rows returned from student table
    $a = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
    $tchrCount = mysqli_num_rows($a);// same but with teachers table
    if($stdCount != 0){
       $row = mysql_fetch_array($result);
       $_SESSION['id'] = $row['id']; //set session for non admin.
   }else if($tchrCount != 0){
      $r = mysql_fetch_array($a);
      $_SESSION['admin'] = $r['id'];
  }else{
         echo "Username and Password is not Matching.";
  }
 }//end of the main if

I have not tested this code so dunno if it works or not but I think you got the logic.

Sanjok Gurung
  • 948
  • 4
  • 17
  • 33
0
  1. use quotes: $row["id"]
  2. "Location: " must be capital.
  3. after calling the "header" function make sure you use "exit".

This code is not tested, but if I understood correctly, should work.

<?php
    session_start();
    $message = "";
    if(count($_POST)>0)
    {
        $conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));

        ((bool)mysqli_query($conn, "USE prosoftl_rcc"));

        $result_student = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
        $row_student  = mysqli_fetch_array($result_student);

        $result_teacher = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
        $row_teacher = mysqli_fetch_array($result_teacher);

        if(is_array($result_student))
        {
            $_SESSION["id"] = $row_student["id"];
            $_SESSION["name"] = $row_student["name"];
            $_SESSION["admin"] = 0;
        }
        elseif(is_array($result_teacher))
        {
            $_SESSION["id"] = $row_teacher["id"];
            $_SESSION["name"] = $row_teacher["name"];
            $_SESSION["admin"] = $row_teacher["id"];
        }
        else
        {
            $message = "Invalid Username or Password!";
        }
    }
    if(isset($_SESSION["id"]))
    {
        if(@$_SESSION["admin"]>0)
        {  header ("Location: gui-admin.php");
           exit;
        }
        else
        {   header("Location: user_dashboard.php");
            exit;
        }
    }
?>

Hope it helps....

Federico
  • 1,231
  • 9
  • 13
0

But I can guess why you are facing the problem for your code only working for students. In this -

if(is_array($row))

is_array($row) would always be returning true and the code goes on to execute

$_SESSION["id"] = $row[id];
$_SESSION["name"] = $row[name];

but $row[id] would be empty because there are no rows matching the criteria, so $_SESSION["id"] would not be assigned and when this is executed -

if(isset($_SESSION["id"]))
    {
        header("Location:user_dashboard.php");
    }
    elseif(isset($_SESSION["admin"]))
    {
        header ("location:gui-admin.php");
    }

None of the if statements would not be executed because none of them are set. This is my analysis. This could be wrong.

Try the solution below -

You should combine the users table for just querying whether the user is a student or a teacher. You then query the student table or the teacher table depending on the Main "Users" table. Querying for the same username and password to two tables doesnt look good.

You can change the meta tag in my code to header("Location: $url") but I would prefer this so that the request doesnt get cached by the user. Hope it helps :-

$sql="SELECT * FROM {$table} WHERE username='{$username}' and password='{$password}'"; //My variables are already filtered and safe from SQL Injection. 

$result=mysqli_query($mysqli, $sql);

if(mysqli_num_rows($result))
{
    $fetch=mysqli_fetch_row($result);
    $_SESSION["id"]=$fetch['userid'];//Just fetching all details
    $_SESSION["Name"]=$fetch['name'];//and making session variables for that.
    $_SESSION["username"]=$fetch['username'];
    $isadmin=$fetch['isadmin']; //is a BOOL value in MySQL table.

        if($isadmin) //checking whether admin or not
        {
            $_SESSION["isadmin"]=1;
            echo "<meta http-equiv='refresh' content='0;url=adminurl'>";    } //if admin redirect to different url
        else{
            $_SESSION["isadmin"]=0;
            echo "<meta http-equiv='refresh' content='0;url=userurl'>";         
        }
}
else
{
    //Username Password Incorrect
    /* Show FORM HERE */
}
Yash Sodha
  • 713
  • 3
  • 13
0

First of all, you have to know that's really a bad idea to use your POST data directly in your SQL request, you have to avoid that and to clean your data using a function like mysqli_real_escape_string. Also, you have to secure your passwords and avoid to save it clear into your DB, for that take a look on the best way to store password in database.

For your two SQL requests, you can use mysqli_multi_query like I did in this example where I used the same script to get POST data and show the login form :

<?php

if(count($_POST) > 0){

    session_start();

    $link = mysqli_connect('localhost', 'user', 'pass', 'db');

    if(mysqli_connect_errno()) {
        die('db connection error : ' . mysqli_connect_error());
    }

    function secure_password($password){
        // secure your password here
        return $password;
    }

    // escape special characters
    $user_name = mysqli_real_escape_string($link, $_POST['user_name']);
    // you have to secure your passwords, when saving it of course
    $password = secure_password(mysqli_real_escape_string($link, $_POST['password']));

    $query  = "SELECT id FROM student WHERE name = '".$user_name."' and password = '".$password."';";
    $query .= "SELECT id FROM teacher WHERE name = '".$user_name."' and password = '".$password."'";

    $is_teacher = FALSE;

    if(count($_SESSION)) session_destroy();

    // you can use mysqli_multi_query for your two requests
    if (mysqli_multi_query($link, $query)) {
        do {
            if ($result = mysqli_store_result($link)) {
                if ($row = mysqli_fetch_row($result)) {
                    if($is_teacher){
                        $_SESSION['admin'] = $row[0];
                    } else {
                        $_SESSION['id'] = $row[0];
                        $_SESSION['name'] = $user_name;
                    }
                }
                mysqli_free_result($result);
            }
            if (mysqli_more_results($link)) {
                // if we have more results, so it's a teacher record
                $is_teacher = TRUE;
            }
        } while (mysqli_more_results($link) && mysqli_next_result($link));
    }
    mysqli_close($link);

    if(isset($_SESSION['id']))
    {
        header('Location:user_dashboard.php');
    }
    elseif(isset($_SESSION['admin']))
    {
        header('Location:gui-admin.php');
    }

    // no redirection, show the message and the login form
    echo 'Invalid Username or Password!';    

} 

?>
<form action='p.php' method='post'>
    User name : <input type='text' name='user_name'><br>
    Password : <input type='password' name='password'><br>
    <input type='submit' value='Submit'>
</form> 

Hope that can help.

Community
  • 1
  • 1
akmozo
  • 9,829
  • 3
  • 28
  • 44