首页 > 解决方案 > Directing users to specific pages on login in PHP

问题描述

In my current project in PHP and MySQL, I have a database of two different user- students and teachers-.

When I enter the username and password, I want the system can differentiate the user is a student or teacher so that it can direct the user to the related page. How can I do that in PHP? Should I create 2 tables in the same database or 2 tables in a different database.

login.php

<?php 

session_start();

// variable declaration
$username = "";
$password ="";
$query = "";
$errors = array(); 
$_SESSION['success'] = "";

// connect to database
$db = mysqli_connect('localhost', 'root', '', 'loginstudent');

// LOGIN USER
if (isset($_POST['login_user'])) {
    $username = mysqli_real_escape_string($db, $_POST['username']);
    $password = mysqli_real_escape_string($db, $_POST['password']);

    if (empty($username)) {
        array_push($errors, "Username is required");
    }
    if (empty($password)) {
        array_push($errors, "Password is required");
    }

    if (count($errors) == 0) {
        $password = md5($password);
        $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
        $results = mysqli_query($db, $query);


        if (mysqli_num_rows($results) == 1) {   
            $_SESSION['username'] = $username;
            header('location: student.html');

        }else {

            array_push($errors, "Wrong username/password combination");
        }
    }
}

?>

标签: phpmysqli

解决方案


To do this correctly you should add a column to your 'users' table. For this example I will call the column user_type and for each user I will store either 'student' or 'teacher'. Starting at the point where you have executed your query:

$results = mysqli_query($db, $query);
$row = mysqli_fetch_assoc($results); // get an associative array from the row returned

if('student' == $row['user_type']) {
    header('Location: student.html');
    exit();
} elseif ('teacher' == $row['user_type']) {
    header('Location: teacher.html');
    exit();
} else {
    // not a valid user
    header('Location: register.html');
    exit();
}

WARNING Under your original post I provided several comments concerning the safety of your code. You should read and follow all of those warnings and learn how to write safe code from the start.


推荐阅读