简体   繁体   中英

php to redirect user based on “role” using mysqli

<?php

$host = 'localhost';
$username = 'admin2';
$password = 'vaptek';
$db_name = 'vaportek_db';


// 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['userId'];
$mypassword=$_POST['userPw'];

$stmt = $db->prepare("SELECT role FROM users 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 ($test == 1) {
    // bind the result to a variable
    $stmt->bind_result($role);
    $stmt->fetch_object()->$role;

    switch( $role ){       

        case 'director':
        header("location: director.php");   
        break;

        case 'customer':
        header("location: cust.php");
        break;

        case 'production manager':
        header("location: prodmanager.php");
        break;

        case 'account admin':
        header("location: accountadmin.php");
        exit();

        default:
        echo "Wrong staff ID or password";
    }
    $stmt->close();
}

$db->close();
?>

When i run the code it just gives me a blank page and doesn't move on from login.php

I have done echo $test = $stmt->affected_rows; which is showing as -1 I am not very familiar with php and dont really understand where it is going wrong .

...

/* execute query */
$stmt->execute();

$res = $stmt->get_result();

// If result matched $myusername and $mypassword, table row must be 1 row
if ($res->num_rows == 1) {

...
if($stmt->execute()){

//Gets the results and assigns it to $result
$result = $stmt->get_result();

//runs a while loop so that the role can be pulled out and assigned to $role for the switch
while($row = $result->fetch_assoc()){
    $role = $row['role'];
}

// If result matched $myuser

Fixed it FINALLY! Thanks for the help you got me in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM