I'm trying to redirect the logged-in user to a different page according to the enum input was stored at db.
I was trying those lines, but it always redirects me at pro.php
. How can I do this with the right way? What is the issue with the code?
Here is my table definition:
# | Name | Type | Null | Default | |
---|---|---|---|---|---|
1 | id | Primary int(11) | No | None | AUTO_INCREMENT |
2 | firstName | varchar(255) | Yes | NULL | |
3 | lastName | varchar(255) | Yes | NULL | |
4 | Index | varchar(255) | Yes | NULL | |
5 | speciality | enum('pro', 'stu') | Yes | NULL | |
6 | password | varchar(100) | Yes | NULL | |
7 | lastLogin | timestamp | Yes | NULL |
Here is the PHP code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include_once("config.php");
include_once("session.php");
if (isset($_POST['signin'])) {
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$errors = array();
if (empty($email)) {
array_push($errors, "email is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM user WHERE email='$email' AND password='$password'";
$results = mysqli_query($conn, $query);
if (mysqli_num_rows($results) == 1)
{
$_SESSION['email'] = $email;
$_SESSION["user_name"]=$firstName;
$_SESSION['success'] = "You are now logged in";
$logintime = "UPDATE user SET lastLogin = now() where email = '$email'";
mysqli_query($conn, $logintime);
//Check speciality and redirect accordingly
$speciality = $row['speciality'];
if($speciality == "stu"){
header("location:stu.php");
}else{header("location:pro.php");}
}else
{
array_push($errors, "Wrong username/password combination");
header("location:login.php");
}
}
}
?>
I know the user is logged in because after the login, i'm going to db and see the lastLogin updated at the current user.
CodePudding user response:
Ok i change the speciality type enum to int(0 or 1) and some more things to the code and now is redirect me properly and almost everything working properly.
if (isset($_POST['submit'])) {
$email = $_POST['email'];
$password = $_POST['password'];
//also i hash the password with a better algorythm
$password = hash('sha256', $password);
$sql = "SELECT * FROM user WHERE email='$email' AND password='$password'";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
$row = mysqli_fetch_assoc($result);
$_SESSION['user_name'] = $row['user_name'];
$logintime = "UPDATE user SET lastLogin = now() where email = '$email'";
mysqli_query($conn, $logintime);
$_SESSION['speciality'] = $row['speciality'];
if($_SESSION['speciality']==1) {header("Location: pro.php");}
else{header("Location: stu.php");}
} else {
echo "<script>alert('Woops! Email or Password is Wrong.')</script>";
}
}