php - 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");
}
}
}
?>
解决方案
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.
推荐阅读
- python - bcrypt 相同字符串的不同哈希?
- r - 在 R 中的 ggplot2 上使用 ConnLines
- c# - 模型 EF Core 的计算属性 - 属性还是方法?
- json - 如何在 clickfunnels 中创建 webhook 以向愿望清单成员发送信息
- ruby - 自动提交 ODBC api 无法通过 IBM iAccess 到 unixODBC 到 ruby-odbc
- zsh - 如何在zsh中用反引号引用字符串?
- curl - curl命令输出带有时间戳的文件名
- xaml - 如何在导航页面的导航栏部分放置图标
- c - 为什么不先分配指针取消引用就不起作用?
- sql - CLEARDB 中 where 和 like 的区别