php根据"角色"重定向用户使用mysqli

时间:2017-05-28 21:14:01

标签: php 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();
?>

当我运行代码时,它只给我一个空白页面,并且不会从login.php继续

我做过echo $ test = $ stmt-&gt; affected_rows;这显示为-1我不熟悉PHP,并不真正了解它出错的地方。

2 个答案:

答案 0 :(得分:0)

...

/* 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) {

...

答案 1 :(得分:0)

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

最后修好了!感谢您的帮助,让您朝着正确的方向前进。