登录后根据用户角色重定向到不同的页面

时间:2016-03-01 17:34:52

标签: php redirect mysqli

我想修改我的代码以在登录后重定向到不同的页面,具体取决于用户角色,我只能进行一次通用重定向,无论角色如何。我需要有关如何实现它的帮助。

这是我的用户数据库表:

userID  fullname    email               role    password
1       Tester one  test@gmail.com      N       ALSJALDDJ6464!JJLSK
2       Tester two  tester@gmail.com    C       @ALSJAL5656DDJJJLSK

我的PHP登录代码在这里:

<?php
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', 1);

// establishing the MySQLi connection

// Create connection
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "timewise";

$conn = new mysqli($localhost, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

// checking the user
if(isset($_POST['btnLogin'])){
$email = mysqli_real_escape_string($conn,$_POST['uemail']);
$pass = mysqli_real_escape_string($conn,$_POST['upass']);

//$pass = crypt($pass);


$sel_user = "SELECT * FROM users WHERE email='$email' AND pass='$pass'";

$run_user = mysqli_query($conn, $sel_user);
if (!$sel_user) {
die(mysqli_error($conn));
}

$check_user = mysqli_num_rows($run_user);

if($check_user>0){
$user_data = mysqli_fetch_assoc($run_user);

if ($user_data["role"] == 'C') {
    //redirect somehwere
    print '<script type="text/javascript">window.location = "index.html"</script>';
} else {
    //redirect somehwere else
    print '<script type="text/javascript">window.location = "form-wizard.html"</script>';
}
} else {
    // more code here
    echo '<center><span style="color:#801b1b; border:1px solid #e5a3a3; background:#ffcfcf; padding:5px;">Email or password is not correct, please try again!</span></center>';
}

}

?>

我需要帮助将登录用户重定向到不同的页面,具体取决于角色,即

  

普通用户为“N”,公司用户为“C”。

2 个答案:

答案 0 :(得分:0)

所以,让我们开始吧:

$sel_user = "SELECT * FROM users WHERE email='$email' AND pass='$pass'";
$run_user = mysqli_query($conn, $sel_user);

// this will never happens as $sel_user is a string and it's not empty
// I suppose you need to check `$run_user`
if (!$sel_user) {
    die(mysqli_error($conn));
} 

$check_user = mysqli_num_rows($run_user);
if($check_user>0){
    // here you need $run_user data
    // use fetch_ methods, for example `fetch_assoc()`
    $user_data = mysqli_fetch_assoc($run_user);
    // print_r($user_data) to check keys
    if ($user_data["role"] == 'C') {
        //redirect somehwere
    } else {
        //redirect somehwere else
    }
} else {
    // more code here
}

答案 1 :(得分:0)

you could use the header('location: /file') function to immediately redirect to a different page according to user position in some if/else or have the link as a variable and it would be header("location: " . $file). I hope that this is helpful!

相关问题