2

I need to redirect users to different pages based on the roles given to them in the database. Only the username and password is submitted on the login page. I have to fetch the role from the database which looks like this:

username  |  password  |  role
xxxxxx       xxxxxx       admin
xxxxxx       xxxxxx       trainer
xxxxxx       xxxxxx       trainer
xxxxxx       xxxxxx       Line Manager

Here is my code:

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form 
$myusername=$_POST['myusername']; 
$mypassword=$_POST['mypassword']; 


$sql="SELECT * FROM login WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

     // Register $myusername, $mypassword and redirect to file "login_success.php"
     $role = mysqli_fetch_array($result);


      if($role == "Admin"){
        header("location:index.php");
            exit();
      }
      elseif($role['role'] == "Trainer"){
  header("location:index1.php");
        exit();
     }
      elseif($role['role'] == "Line Manager"){
  header("location:index2.php");
        exit();
     }
      elseif($role['role'] == "Client"){
  header("location:client.php");
        exit();
     }


  }
     else {
        echo "Wrong Username or Password"; 
     }
?>
Herbert
  • 5,698
  • 2
  • 26
  • 34
user2612747
  • 37
  • 1
  • 2
  • 5
  • ok tell us more. that seems to work ok, i would use a switch block instead of the if – DevZer0 Jul 26 '13 at 08:54
  • Read up on [ACL's](https://en.wikipedia.org/wiki/Access_control_list) to get a better idea of what you need to do. Also, it isn't clear what you are asking us here as there is no actual question. – vascowhite Jul 26 '13 at 08:56
  • possible duplicate of [ACL implementation](http://stackoverflow.com/questions/3430181/acl-implementation) – vascowhite Jul 26 '13 at 08:58
  • 2
    header location should URI. not a file name. use that file with base url. – Dinuka Thilanga Jul 26 '13 at 09:01
  • 1
    it doesnt work, the page remain, without any redirection, could you show me how the switch block would work with my codes – user2612747 Jul 26 '13 at 09:02
  • So debug it! check if count = 1, then check what you have in the role variable and see why it is not matching what you expect it to do. Try echoing or print_r() ing some of your data – Anigel Jul 26 '13 at 09:04
  • 1
    The first `if` checks `$role` while the others check `$role['role']`. You probably want the latter – Herbert Jul 26 '13 at 09:07

1 Answers1

3

In your code, the first if statement checks $role while the others check $role['role']. My guess is that you're trying to log in as "Admin" and that's why it's not working.

Update

There was far more wrong with your code than I initially realized.

  1. You're mixing mysql_* functions with mysqli_* functions. Not only is this wrong, but mysql_* functions have been deprecated. You should no longer use them.

  2. You're leaving yourself open to SQL Injection by using POST variables directly in your select statement. The way to fix this is by using prepared statements.

Disclaimer: I haven't used mysqli in quite some time so the code presented here may contain errors.

<?php
// Connect to server and select database.
$db = new mysqli($host, $username, $password, $db_name);

if( $db->connect_errno ){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

// username and password sent from form 
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

if ($stmt = $db->prepare("SELECT role FROM login WHERE `username`=? and `password`=?")) {
    /* bind parameters for username and password */
    $stmt->bind_param('ss', $myusername, $mypassword);

    /* execute query */
    $stmt->execute();
    
    // If result matched $myusername and $mypassword, table row must be 1 row
    if ($stmt->affected_rows == 1) {
        // bind the result to a variable
        $stmt->bind_result($role);
        $stmt->fetch();
        
        switch( $role ){

            case 'Admin':
                header("location:index.php");
                exit();

            case 'Trainer':
                header("location:index1.php");
                exit();

            case 'Line Manager':
                header("location:index2.php");
                exit();

            case 'Client':
                header("location:client.php");
                exit();

            default:
                echo "Wrong Username or Password";
        }
    
    }

    $stmt->close();
}

$db->close();

?>

I personally prefer PDO (illustrated below). I haven't tested the code so it too may not be completely accurate, but it should get you on the right path.

<?php
// username and password sent from form 
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

try {
    // Connect to server and select database.
    $db = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
    $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    
    $stmt = $db->("SELECT *, COUNT(*) as count FROM login WHERE `username`=:user and `password`=:pass");
    $stmt->bindParam(':user', $myusername);
    $stmt->bindParam(':pass', $mypassword);
    
    if ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
        $count = $row['count'];
        
        // If result matched $myusername and $mypassword, table must be 1 row
        if ($count == 1) {        
            switch( $row['role'] ){

                case 'Admin':
                    header("location:index.php");
                    exit();

                case 'Trainer':
                    header("location:index1.php");
                    exit();

                case 'Line Manager':
                    header("location:index2.php");
                    exit();

                case 'Client':
                    header("location:client.php");
                    exit();

                default:
                    echo "Wrong Username or Password";
            }
        }
    }
    
    $db = null;
}

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

?>

For more on PDO, see: Why you Should be using PHP’s PDO for Database Access

Community
  • 1
  • 1
Herbert
  • 5,698
  • 2
  • 26
  • 34