You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何根据数据库存储的enum字段值实现登录用户不同页面跳转

问题原因
  • 核心错误:执行SELECT用户查询得到结果集$results后,没有调用mysqli_fetch_assoc()(或同类结果解析函数)将结果集转为数组,代码中用到的$row属于未定义变量,$row['speciality']永远为空,因此判断条件永远不成立,始终走else分支跳转至pro.php。
  • 次要错误:$_SESSION["user_name"] = $firstName中的$firstName也未赋值,属于未定义变量,存入session的用户名称会为空。
  • 优化建议:跳转后建议新增exit()终止后续代码执行,避免逻辑异常;当前使用md5加密密码安全性极低,且直接拼接SQL语句存在SQL注入风险,后续可改用预处理查询+password_hash/password_verify做密码校验。
正确实现代码
<?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) 
    {
      // 新增代码:解析查询结果为关联数组
      $row = mysqli_fetch_assoc($results);
      // 新增代码:从结果中取firstName赋值
      $firstName = $row['firstName'];

      $_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");
        // 新增代码:跳转后终止执行
        exit();
      }else{
        header("location:pro.php");
        exit();
      }
    }else 
    {
        array_push($errors, "Wrong username/password combination");
        header("location:login.php");
        exit();
    }
  }
}
?>

内容的提问来源于stack exchange,提问作者pos3id0nas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 16:45:06