我正在建立一个网站,我想要检索数据库中定义的用户类型,并将登录用户重定向到特定页面。例如,如果用户是admin,则会将该人员重定向到管理页面,如果用户类型为X,则会将该用户重定向到用户类型X的特定页面。
目前,我正在尝试临时解决方案,因为我没有足够的时间直到截止日期(明天)。我试图通过运行数据库和php查询从数据库中获取用户类型,如下所示:
$_SESSION['login'] = true;
$_SESSION['username']=$username;
$query="select user_type from ".$table_name." where username='$username'";
$result=mysqli_query($con,$query) or die('error');
if(mysqli_num_rows($result))
{
$_SESSION['user_type']=$user_type;
}
echo json_encode( array('result'=>1));
我可以获取用户名和登录状态,但是当我试图获取用户类型时,我在_SESSIONS数组上得到一个空结果。
整个php代码如下:
<?php
session_start();
include("db.php");
$con=mysqli_connect($server, $db_user, $db_pwd,$db_name) //connect to the database server
or die ("Could not connect to mysql because ".mysqli_error());
mysqli_select_db($con,$db_name) //select the database
or die ("Could not select to mysql because ".mysqli_error());
//prevent sql injection
$username=mysqli_real_escape_string($con,$_POST["username"]);
$password=mysqli_real_escape_string($con,$_POST["password"]);
//$user_type=mysqli_real_escape_string($con,$_POST["user_type"]);
//decrypt password
//check if user exist already
$query="select * from ".$table_name." where username='$username'";
$result=mysqli_query($con,$query) or die('error');
if (mysqli_num_rows($result)) //if exist then check for password
{
//Pickup password to compare with encrypted password
$query="select password from ".$table_name." where username='$username'";
$result=mysqli_query($con,$query) or die('error');
$db_field = mysqli_fetch_assoc($result);
$hashed_password=crypt($password,$db_field['password']);
$query="select * from ".$table_name." where username='$username' and password='$hashed_password'";
$result=mysqli_query($con,$query) or die('error');
if (mysqli_num_rows($result)) //if passwords match then check actvation status
{
$query="select * from ".$table_name." where username='$username' and password='$hashed_password' and activ_status in(1)";
$result=mysqli_query($con,$query) or die('error');
if(mysqli_num_rows($result))
{
$_SESSION['login'] = true;
$_SESSION['username']=$username;
$query="select user_type from ".$table_name." where username='$username'";
$result=mysqli_query($con,$query) or die('error');
if(mysqli_num_rows($result))
{
$_SESSION['user_type']=$user_type;
}
echo json_encode( array('result'=>1));
}
else
{
echo json_encode( array('result'=>"$msg_email_1 <br /><a href=\"".$url."\\resend_key.php?user=".$username."\">$msg_email_2</a>."));
// echo "User Account not yet activated.Check your mail for activation details.";
}
}
else
{
echo json_encode( array('result'=>$msg_pwd_error));
// echo trim("password incorrect");
}
}
else
{
echo json_encode( array('result'=>$msg_un_error));
// die("Username Doesn't exist");
die();
}
?>
如果你可以帮助我,我真的很感激。
非常感谢。
答案 0 :(得分:2)
您有$_SESSION['user_type'] = $user_type
但$user_type
是什么?您没有在任何地方初始化它,因此$_SESSION['user_type']
中不会存储任何内容。
您必须首先从数据库中获取结果,然后将结果的值分配给$user_type
变量,然后才能存储它。
$row = mysqli_fetch_assoc($result);
$user_type = $row['user_type'];